有人可以解釋為什么當(dāng)切片傳遞給可變參數(shù)函數(shù)時鴨子類型不起作用。如下所示的情況 1 和 2 似乎有效,但下面的情況 3 初始化一個切片,然后將取消引用的切片傳遞給接受接口的函數(shù)。錯誤信息是: cannot use gophers (type []Gopher) as type []Animal in argument to runForestpackage 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...) }
接口和類型的問題
ibeautiful
2021-12-13 18:44:42