英文:
How to call method which accepts slice of interface as parameters in golang?
问题
我想在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
英文:
I want to call a method which accepts slice of interface as paramers in golang, but I find that I cannot pass it write as this:
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)
}
I get error like this:
cannot use s (type []*A) as type []Base in argument to foo2
答案1
得分: 5
如果函数接受一个[]Base
参数,你必须传递一个[]Base
参数。不是[]interface{}
,也不是[]thingThatImplementsBase
,而是明确的[]Base
类型。接口的切片不是一个接口 - 它不是由任何其他类型的切片“实现的”。接口切片的元素可以是任何实现该接口的类型,但切片本身是一个严格而具体的类型。
英文:
If the function takes a []Base
parameter, you must pass a []Base
parameter. Not a []interface{}
, not a []thingThatImplementsBase
, but specifically a []Base
. A slice of interfaces isn't an interface - it isn't "implemented by" a slice of any other type. The elements of a slice of interfaces can be anything that implements the interface, but the slice itself is of a strict and specific type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论