结构体Dog实现了接口的所有方法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
3 回答
30秒到达战场
TA贡献1828条经验 获得超6个赞
您必须从界面中删除指针。
//Animal interface
type Animal interface {
run()
}
//Dog struct
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.name = "Putty"
d.run()
a = d //errors here
a.run()
}
- 3 回答
- 0 关注
- 129 浏览
添加回答
举报
0/150
提交
取消