我正在尝试将指向结构的指针添加到切片,但我无法摆脱此错误:
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()
}