doujianglin6704 2017-06-01 09:05
浏览 254
已采纳

如何在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 09: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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部