Dog
结构体实现了接口(interface)Animal
的所有方法,为什么*Dos
不能赋值给*Animal
?
type Animal interface {
run()
}
type Dog struct {
name string
}
func (d *Dog) run() {
fmt.Println( d.name , " is running")
}
func main(){
var d *Dog
var a *Animal
d = new(Dog)
d.run()
a = d //errors here
}
Go 通知以下错误:
Cannot use 'd' (type *Dog) as type *Animal in assignment
最佳答案
具有接口(interface)类型的变量已经是指针;您不需要将其声明为指向接口(interface)的指针。只需执行 var a Animal
即可。
关于go - 无法将结构指针分配给接口(interface)指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54489752/