go - 无法将结构指针分配给接口(interface)指针

标签 go struct interface polymorphism

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/

相关文章:

c - 在 C 中,将文本文件读入结构数组,然后用该数组写入新的文本文件

go - 在函数调用中传递带有参数的类型

postgresql - 使用 docker-compose 时如何从 golang 应用程序连接到 postgres?

C 错误 :format '%s' expects argument of type 'char *' but argument 2 has type 'char (*)[100]'

vb.net - 为什么 Visual Studio 2012 不允许您在创建新的 VB.NET 文件时选择结构?结构是否已弃用?

接口(interface)中的java泛型子类型

c# - 实例化泛型类时如何避免指定冗余类型

java - 接口(interface)类型的实例变量无法访问实现类的方法,而实现类类型的实例变量可以访问

go - 如何解决本地模块的传递依赖

go - 如何将嵌入式接口(interface)分配给golang中的对象