func(b boy)eat() { fmt.Println("The boy is eating an apple") }
type girl struct { }
func(g girl)eat() { fmt.Println("The girl is eating an orange") }
type human struct { b boy girl // 匿名字段 }
func(h human)eat() { fmt.Println("The man is eating some strawberries") }
funcmain() { var h human h.b.eat() h.girl.eat() h.eat() }
这个demo仅比上个例子多了一个human的eat方法
执行结果:
1 2 3
The boy is eating an apple The girl is eating an orange The man is eating some strawberries
这次的执行结果中, h.eat() 的执行结果不再是 The girl is eating an orange, 而是 The man is eating some strawberries. 说明human下定义的eat方法重写了组合中同名的eat方法, 当该方法被直接调用时, 优先执行human下的eat方法. 此时如果还需要执行girl下的eat方法, 则需要先引用其数据类型, 再调用eat方法 -> h.girl.eat()