去嵌入 : method not inherited

标签 go

我正在尝试 golang 嵌入,但以下代码无法编译:

type Parent struct {}

func (p *Parent) Foo() {
}

type Child struct {
    p *Parent
}

func main() {
    var c Child
    c.Foo()
}

./tmp2.go:18:3: c.Foo undefined (type Child has no field or method Foo)

我做错了什么?

最佳答案

写作时:

type Child struct {
    p *Parent
}

您没有嵌入Parent,您只是声明了一些 *Parent 类型的实例变量 p

要调用 p 方法,您必须将调用转发给 p

func (c *Child) Foo() {
    c.p.Foo()
}

通过嵌入你可以避免这种簿记,语法将是

type Child struct {
    *Parent
}

关于去嵌入 : method not inherited,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53796786/

相关文章:

pointers - 如何检查嵌套指针访问/方法在运行时是否无效

go - 如何上传 gzip 压缩文件而不将所有内容读入内存

go - Golang 中具体类型的错误片段

go - 为结构字段创建函数类型

go - GORM 是否有 Decimal 数据类型?

Codewalk之Golang并发代码回顾

Golang,有没有更好的方法将整数文件读入数组?

戈朗 : Testing with init() func

go - 使用brew安装fluxctl

go - 从文件名中删除路径