我想在 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)
}
Run Code Online (Sandbox Code Playgroud)
我收到这样的错误:
cannot use s (type []*A) as type []Base in argument to foo2
Run Code Online (Sandbox Code Playgroud)
如果函数带有[]Base参数,则必须传递[]Base参数。不是一个[]interface{},不是一个[]thingThatImplementsBase,而是具体的一个[]Base。接口切片不是接口 - 它不是由任何其他类型的切片“实现”。接口切片的元素可以是实现接口的任何元素,但切片本身具有严格且特定的类型。