如何在golang中调用接受切片接口的方法作为参数?

时间:2017-06-01 17:05:15

标签: go interface

我想在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

1 个答案:

答案 0 :(得分:1)

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