有人可以解释为什么在将 slice 传递给可变参数函数时鸭子类型不起作用。
如下所示的情况 1 和 2 似乎可行,但下面的情况 3 初始化一个 slice ,然后将取消引用的 slice 传递给接受接口(interface)的函数。
错误信息是: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...)
}
最佳答案
正如 Volker 在评论中提到的那样, slice 不能像其元素那样进行隐式转换。 Gopher
可以像 Animal
一样嘎嘎叫,但是 []Gopher
不能像 []Animal
.
实现此功能的最小更改是:
func main() {
gophers := []Gopher{{}, {}}
out := make([]Animal, len(gophers))
for i, val := range gophers {
out[i] = Animal(val)
}
runForest(out...)
}
关于go - 接口(interface)和类型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35443292/