【问题标题】:How to call method which accepts slice of interface as parameters in golang? [duplicate]go - 如何在golang中调用接受接口切片作为参数的方法? [复制]
【发布时间】:2017-06-01 17:05:15
【问题描述】:

我想在golang中调用一个接受接口切片作为参数的方法,但是我发现我不能这样传递它:

type Base interface {
    Run()
}

type A struct {
    name string
}

func (a *A) Run() {
    fmt.Printf("%s is running\n", a.name)
}

func foo1(b Base) {
    b.Run()
}

func foo2(s []Base) {
    for _, b := range s {
        b.Run()
    }
}

func TestInterface(t *testing.T) {
    dog := &A{name: "a dog"}
    foo1(dog)
    // cat := A{name: "a cat"}
    // foo1(cat)
    s := []*A{dog}
    foo2(s)
}

我收到这样的错误:

cannot use s (type []*A) as type []Base in argument to foo2

【问题讨论】:

标签: go interface


【解决方案1】:

如果函数采用[]Base 参数,则必须传递[]Base 参数。不是[]interface{},不是[]thingThatImplementsBase,而是特别是[]Base。接口切片不是接口——它不是由任何其他类型的切片“实现”的。接口切片的元素可以是任何实现该接口的元素,但切片本身是严格且特定的类型。

【讨论】:

    猜你喜欢
    • 2016-12-20
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多