接口和类型的问题

时间:2016-02-16 21:25:03

标签: go

当有人将切片传递给可变参数函数时,有人可以解释为什么鸭子打字不起作用 如下所示的情况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...)
    }

1 个答案:

答案 0 :(得分:2)

正如Volker在评论中提到的那样,切片不能以其元素的方式被隐式转换。 Gopher可以像Animal一样嘎嘎叫,但[]Gopher不能像[]Animal一样嘎嘎作响。

实现这一目标的最小变化是:

func main() {
    gophers := []Gopher{{}, {}}
    out := make([]Animal, len(gophers))
    for i, val := range gophers {
        out[i] = Animal(val)
    }
    runForest(out...)
}