当前位置:网站首页>方法的繼承和重寫
方法的繼承和重寫
2022-06-21 12:10:00 【attempt_to_do】
繼承
如果匿名字段實現了一個method,那麼包含這個匿名字段的struct也能調用該method。
package main
import "fmt"
type Human struct {
name string
age int
phone string
}
type Student struct {
Human //匿名字段
school string
}
type Employee struct {
Human //匿名字段
company string
}
//在human上面定義了一個method
func (h *Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
func main() {
mark := Student{
Human{
"Mark", 25, "222-222-YYYY"}, "MIT"}
sam := Employee{
Human{
"Sam", 45, "111-888-XXXX"}, "Golang Inc"}
mark.SayHi()
sam.SayHi()
}
重寫
如果Employee想要實現自己的SayHi,怎麼辦?簡單,和匿名字段沖突一樣的道理,我們可以在Employee上面定義一個method,重寫了匿名字段的方法。
package main
import "fmt"
type Human struct {
name string
age int
phone string
}
type Student struct {
Human //匿名字段
school string
}
type Employee struct {
Human //匿名字段
company string
}
//Human定義method
func (h *Human) SayHi() {
fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
}
//Employee的method重寫Human的method
func (e *Employee) SayHi() {
fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
e.company, e.phone) //Yes you can split into 2 lines here.
}
func main() {
mark := Student{
Human{
"Mark", 25, "222-222-YYYY"}, "MIT"}
sam := Employee{
Human{
"Sam", 45, "111-888-XXXX"}, "Golang Inc"}
mark.SayHi()
sam.SayHi()
}
边栏推荐
猜你喜欢

Compilation de l'environnement vs Code + GCC développé par stm32

Jenkins configures scheduled tasks through build periodically

It is the German oscilloscope software and the keysight oscilloscope upper computer software ns-scope

Sdcc compiler + vscode to develop 8-bit microcontroller

20n10-asemi medium and low voltage MOS tube 20n10

华为是如何从0到1打造以项目为中心运作的项目管理体系的?

Is 100W data table faster than 1000W data table query?

看懂UML类图和时序图

Apache shardingsphere 5.1.2 release | new driving API + cloud native deployment to create a high-performance data gateway

华为云发布桌面IDE-CodeArts
随机推荐
harmonyos培訓一
Snow Ice City (blackened)
Rectangular coverage area
2-zabbix automatically add hosts using autodiscover
harmonyos培训一
The final battle of the giant: instant retailing
Architect training plan - infinite thinking - variables
The k-th small__
【综合笔试题】难度 2.5/5 :「树状数组」与「双树状数组优化」
Typescript variable declaration - type assertion
Guangdong issues product testing coupons, and consumers also share
Sdcc compiler + vscode to develop 8-bit microcontroller
Standing at the digital tuyere, how can tooling enterprises "fly"
MySQL-DDL
Heavyweight, mapstruct 1.5 was released. This time, it finally supports the transformation of map into bean!
浅论OCA\UV-OCA LOCA\SLOCA 四种全贴合工艺
How does Huawei build a project centered project management system from 0 to 1?
It is the German oscilloscope software and the keysight oscilloscope upper computer software ns-scope
[comprehensive pen test] sword finger offer II 114 Alien dictionary
MySQL 5.6.49 企业版设置密码复杂度策略