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

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

How to call method which accepts slice of interface as parameters in golang?

问题

我想在golang中调用一个接受接口切片作为参数的方法,但我发现我不能像这样直接传递它:

  1. type Base interface {
  2. Run()
  3. }
  4. type A struct {
  5. name string
  6. }
  7. func (a *A) Run() {
  8. fmt.Printf("%s is running\n", a.name)
  9. }
  10. func foo1(b Base) {
  11. b.Run()
  12. }
  13. func foo2(s []Base) {
  14. for _, b := range s {
  15. b.Run()
  16. }
  17. }
  18. func TestInterface(t *testing.T) {
  19. dog := &A{name: "a dog"}
  20. foo1(dog)
  21. // cat := A{name: "a cat"}
  22. // foo1(cat)
  23. s := []*A{dog}
  24. foo2(s)
  25. }

我得到了这样的错误:

  1. 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:

  1. type Base interface {
  2. Run()
  3. }
  4. type A struct {
  5. name string
  6. }
  7. func (a *A) Run() {
  8. fmt.Printf("%s is running\n", a.name)
  9. }
  10. func foo1(b Base) {
  11. b.Run()
  12. }
  13. func foo2(s []Base) {
  14. for _, b := range s {
  15. b.Run()
  16. }
  17. }
  18. func TestInterface(t *testing.T) {
  19. dog := &A{name: "a dog"}
  20. foo1(dog)
  21. // cat := A{name: "a cat"}
  22. // foo1(cat)
  23. s := []*A{dog}
  24. foo2(s)
  25. }

I get error like this:

  1. 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:

确定