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.

图片转代码服务由CSDN问答提供 功能建议

我使用的库的类型具有多种方法:

 输入Foo struct {
} 
 
func(f * Foo)method1()int {...} 
func(f * Foo)method2()int {...} 
func(f * Foo)method3  ()int {...} 
 // ...等等
   
 
 

我真的想在我每次调用 method1 在此类型上:

  func(f * Foo)method1Wrapper()int {
crementCounter()
返回f.method1()
  } 
   
 
 

但这会添加一个 new 方法,我不得不调用 而不是直接调用< code> method1()本身。

或者,我想我可以创建自己的类型:

  type Foo2结构 {
 Foo 
} 
 
func(f * Foo2)method1()int {
增量计数器()
返回f.Foo.method1()
} 
   \  n 
 

但是然后我必须创建一堆样板代码来代理对 method2 method3 等的所有调用 在 Foo 实现中,我必须将所有 Foo 的用法更改为 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

    点赞 打赏 评论

相关推荐 更多相似问题