有人可以解释为什么当切片传递给可变参数函数时鸭子类型不起作用。
如下所示的情况 1 和 2 似乎有效,但下面的情况 3 初始化一个切片,然后将取消引用的切片传递给接受接口的函数。
错误信息是: cannot use gophers (type []Gopher) as type []Animal in argument to runForest
package main
import (
"fmt"
)
type Animal interface {
Run() string
}
type Gopher struct {
}
func (g Gopher) Run() string {
return "Waddle.. Waddle"
}
func runForest(animals ...Animal) {
for _, animal := range animals {
fmt.Println(animal.Run())
}
}
func main() {
//works
runForest(Gopher{})
//works
runForest(Gopher{},Gopher{})
// does not work
gophers := []Gopher{{},{}}
runForest(gophers...)
}
喵喵时光机
相关分类