1.1 method继承
method是可以继承的,如果匿名字段实现了一个method,那么包含这个匿名字段的struct也能调用该method
package mainimport "fmt"type Human struct { name string age int phone string}type Student struct { Human //匿名字段 school string}type Employee struct { Human //匿名字段 company string}func (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %sn", 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()}运行结果:
Hi, I am Mark you can call me on 222-222-YYYYHi, I am Sam you can call me on 111-888-XXXX
1.2 method重写
package mainimport "fmt"type Human struct { name string age int phone string}type Student struct { Human //匿名字段 school string}type Employee struct { Human //匿名字段 company string}//Human定义methodfunc (h *Human) SayHi() { fmt.Printf("Hi, I am %s you can call me on %sn", h.name, h.phone)}//Employee的method重写Human的methodfunc (e *Employee) SayHi() { fmt.Printf("Hi, I am %s, I work at %s. Call me on %sn", 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()}运行结果:
Hi, I am Mark you can call me on 222-222-YYYYHi, I am Sam, I work at Golang Inc. Call me on 111-888-XXXX
方法是可以继承和重写的存在继承关系时,按照就近原则,进行调用



