dongxu7408 2015-10-27 21:21
浏览 19
已采纳

嵌入结构以覆盖方法

TL;DR See playground link at bottom.

I have methods defined on a Manager struct which contains a Context. The Managers are versioned, allowing a new version to only define functions which have changed, and automatically use the functions from the old version if they are not redefined.

type Context struct { ... }

type Manager1 struct{
    Context Context
}

type Manager2 struct {
    Manager1
    Context Context
}

When calling a function on Manager2 which is not defined on Manager2 the Context is nil. Is there a way to do this where the context will be available?

This example demonstrates the problem better than I can explain it: http://play.golang.org/p/gFe6GgUKEJ

  • 写回答

3条回答 默认 最新

  • dousong1926 2015-10-27 21:34
    关注

    You're misusing embedding. The thing is, you've defined Context on Manager1, in spite of that you've redefined it on each subsequent type. In Manager3 you're setting the value for it's Context instance. When Hello() is called, it's defined on Manager2 and accesses it's Context instance which doesn't have a value. Check out this example to demonstrate that http://play.golang.org/p/XebShA9ap4

    Money line is: m3 = Manager3{Manager2: Manager2{Context: Context{Value: "testing3"}}}

    As you can see, if I instantiate the Manager2 instance embedded in Manager3 and set it's Context value it gets printed. I would recommend changing your types so that Context is only defined on Manager1 and then use syntax like that in my example when you initialize your types.

    EDIT: To put the design discussed in comments in writing, you would change your types to this;

    type Context struct {
        Value string
    }
    
    type Manager1 struct {
        Context Context
    }
    
    type Manager2 struct {
        Manager1
    }
    
    type Manager3 struct {
        Manager2
    }
    

    Delete the implementation of Hello() on Manager2 altogether. Then update your composite-literal initialization to this;

    m1 := Manager1{Context: Context{Value: "testing1"}}
    m2 := Manager2{Manager1: Manager1{Context: Context{Value: "testing2"}}}
    m3 := Manager3{Manager2: Manager2{Manager1: Manager1{Context: Context{Value: "testing3"}}}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示