在Go中,是否可以有一个指向带参数的成员函数/方法的指针?
问题描述:
If I have
type Foo struct {
// some data
}
func (f *Foo) Op1() bool {
// perform operation and return a bool
}
func (f *Foo) Op2(other int) bool {
// perform a different operation using internal data
// and the passed in parameter(s)
}
I know I can store a pointer to the first method.
fn := f.Op1
and call it
if fn(f) { // do something }
But what if I want to do the same with Op2
?
I am currently faking it by defined a wrapper function which takes a Foo
and the values and calls the operation. But that is a lot of boiler plate code.
如果我有 p>
类型Foo struct {
/ /一些数据
}
func(f * Foo)Op1()bool {
//执行操作并返回bool
}
func(f * Foo)Op2(other int)bool {\ n //使用内部数据执行不同的操作
//和传入的参数
}
code> pre>
我知道我可以存储指向 第一种方法。 p>
fn:= f.Op1
code> pre>
并调用 p>
如果fn(f){//做某事}
code> pre>
但是如果我想对 Op2做同样的事情怎么办 code>?
我目前正在通过定义一个包装函数来伪造它,该包装函数接受 Foo code>和值并调用该操作。 但这是很多样板代码。 p>
div>
答
Using method expressions
In this case, we get a reference from the type, then you need to pass an instance as the first argument.
fn2 := (*Foo).Op2
f := &Foo{}
fn2(f, 2)
Referencing an instance method
In this case, the instance is already bind to the method and you can just provide the arguments:
fn2 := f.Op2
fn2(2)
Playground: https://play.golang.org/p/e0gUIHzj7Z