duanjiu4498 2018-12-15 20:01
浏览 4
已采纳

嵌入:方法未继承

I'm giving a try to golang embedding and the following code doesn't compile:

type Parent struct {}

func (p *Parent) Foo() {
}

type Child struct {
    p *Parent
}

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

with

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

What I am doing wrong?

  • 写回答

2条回答 默认 最新

  • doucai5315 2018-12-15 20:25
    关注

    When you are writing:

    type Child struct {
        p *Parent
    }
    

    You aren't embedding Parent, you just declare some instance var p of type *Parent.

    To call p methods you must forward the call to p

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

    By embedding you can avoid this bookkeeping, and the syntax will be

    type Child struct {
        *Parent
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料