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 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数