1

我正在尝试将指向结构的指针添加到切片,但我无法摆脱此错误:

cannot use NewDog() (type *Dog) as type *Animal in append:
    *Animal is pointer to interface, not interface

我怎样才能避免这个错误?(仍然使用指针)

package main

import "fmt"

type Animal interface {
  Speak()
}

type Dog struct {
}

func (d *Dog) Speak() {
  fmt.Println("Ruff!")
}

func NewDog() *Dog {
  return &Dog{}
}

func main() {
  pets := make([]*Animal, 2)
  pets[0] = NewDog()
  (*pets[0]).Speak()
}
4

2 回答 2

5
package main

import "fmt"

type Animal interface {
  Speak()
}

type Dog struct {
}

func (d *Dog) Speak() {
  fmt.Println("Ruff!")
}

func NewDog() *Dog {
  return &Dog{}
}

func main() {
  pets := make([]Animal, 2)
  pets[0] = NewDog()
  pets[0].Speak()
}

您不需要指向 Animal 接口的 Slice 指针。

http://golang.org/doc/effective_go.html#pointers_vs_values

于 2013-06-21T07:36:32.513 回答
2

只需将您的代码更改为:

func main() {
  pets := make([]Animal, 2)
  pets[0] = NewDog()
  pets[0].Speak()
}

接口值已经是隐式指针。

于 2013-06-21T07:47:01.030 回答