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

huangapple go评论72阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年6月2日 01:05:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/44313364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定