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.
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