我正在尝试将一个结构的指针添加到切片中,但我无法摆脱这个错误:
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()
}
答案 0 :(得分: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接口的指针。
答案 1 :(得分:2)
只需将您的代码更改为:
func main() {
pets := make([]Animal, 2)
pets[0] = NewDog()
pets[0].Speak()
}
接口值已经是隐式指针。