doujianglin6704
2017-06-01 17:05
浏览 237
已采纳

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

This question already has an answer here:

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
", 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
</div>
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanao3204 2017-06-01 17:12
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题