怎么知道Dog和Cat就实现了Behavior接口呢?
这样写的确是实现了多态,但Dog和Cat并没有显式实现Behavior这个接口,而编译器就已经将其做了关联。为什么不需要像Java一样的implements 显式实现接口?
func main() { dog := Dog{Name: "wangwang", Age: 2} cat := Cat{Name: "mimi", Age: 2} fmt.Println(dog.Eat()) fmt.Println(dog.Run()) fmt.Println(cat.Eat()) fmt.Println(cat.Run()) } type Animal struct { Kind string } type Cat struct { Animal Name string Age int } func (cat *Cat) Eat() string { return "cat: eat" } func (cat *Cat) Run() string { return "cat: run" } type Dog struct { Animal Name string Age int } func (dog *Dog) Eat() string { return "dog: eat" } func (cat *Dog) Run() string { return "dog: run" } type Behavior interface { Eat() string Run() string }