dpg78570 2018-06-29 22:04
浏览 20
已采纳

在类型结构上包装许多方法之一?

A library I use has a type with multiple methods:

type Foo struct {
}

func (f *Foo) method1() int { ... }
func (f *Foo) method2() int { ... }
func (f *Foo) method3() int { ... }
// ... and so on

I'd really like to apply some specific behavior anytime I call method1 on this type:

func (f *Foo) method1Wrapper() int {
    incrementCounter()
    return f.method1()
}

But this adds a new method I'd have to call instead of just directly calling method1() itself.

Alternatively, I imagine I could create my own type:

type Foo2 struct {
    Foo
}

func (f *Foo2) method1() int {
    incrementCounter()
    return f.Foo.method1()
}

But then I'd have to create a bunch of boilerplate code to proxy all the calls to method2, method3, etc down to the Foo implementation, and I'd have to change all my usages of Foo to Foo2.

  • 写回答

1条回答 默认 最新

  • dongyou9373 2018-06-29 22:20
    关注

    You don't need to proxy the method calls to delegate them, this is exactly what embedding is for.

    type Foo struct {
    }
    
    func (f *Foo) method1() int { return 1 }
    func (f *Foo) method2() int { return 2 }
    func (f *Foo) method3() int { return 3 }
    
    type Foo2 struct {
        *Foo
    }
    
    func (f Foo2) method1() int {
        fmt.Println("WRAPPED")
        return f.Foo.method1()
    }
    

    Foo2 has the same method set as Foo, but method1 is "intercepted" by Foo2, which explicitly calls Foo.method1 internally.

    https://play.golang.org/p/q8tea5ZuHl4

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题