iMARS
//定义一个抽象的动物类接口
type IAnimal interface {
Say(msg string) string
}
type Duck struct {
Name string
}
type Dog struct {
Name string
}
func (duck *Duck) Say(msg string) string {
return fmt.Sprintf("duck duck! my name is %s,%s", duck.Name, msg)
}
func (dog *Dog) Say(world string) string {
return fmt.Sprintf("wang wang! my name is %s,%s", dog.Name, msg)
}
func TestAnimal(t *testing.T) {
dog1 := Dog{Name: "Kitty"}
var zoo = make([]IAnimal, 10, 20)
animal := append(zoo, dog1)
t.Log(animal)
}
为何最后两句会报 cannot use dog1 (type Dog) as type IAnimal in append:
Dog does not implement IAnimal (Say method has pointer receiver)
求指点!谢谢。
作者回复: 这里要用指针才行: animal := append(zoo, &dog1)