给定以下 Go 代码:
package main
type CatToy interface {
Rattle() string
}
type Cat struct {
}
func (cat *Cat) Play(catToy CatToy) {
println("The cat is playing!", catToy.Rattle())
}
type DogToy interface {
Roll() string
}
type Dog struct {
}
func (dog *Dog) Play(dogToy DogToy) {
println("The dog is playing!", dogToy.Roll())
}
type SuperToy struct {
}
func (toy *SuperToy) Rattle() string {
return "Rattle!!!"
}
func (toy *SuperToy) Roll() string {
return "Rolling..."
}
type Pet interface {
Play(toy interface{})
}
func main() {
cat := &Cat{}
dog := &Dog{}
superToy := &SuperToy{}
// Working
cat.Play(superToy)
dog.Play(superToy)
// Not Working
pets := []Pet{cat, dog}
for _, pet := range pets {
pet.Play(superToy)
}
}
我收到这些错误:
# command-line-arguments
./main.go:65:16: cannot use cat (type *Cat) as type Pet in array or slice literal:
*Cat does not implement Pet (wrong type for Play method)
have Play(CatToy)
want Play(interface {})
./main.go:65:21: cannot use dog (type *Dog) as type Pet in array or slice literal:
*Dog does not implement Pet (wrong type for Play method)
have Play(DogToy)
want Play(interface {})
SuperToy
实现CatToy
和DogToy
。_ 但是,当我创建一个Pet
以 interface 作为参数的接口时,我得到一个错误。我可以知道我怎样才能得到一个里面有猫和狗的数组/切片吗?我想遍历这个切片并为每个切片调用一个函数。我也想保留CatToy
和DogToy
接口。我也可以删除Pet
接口。
更多信息:将来,我更有可能添加更多pets
. 我认为我不会添加更多操作,例如Play
.
谢谢