Apologies if this is obvious; relatively new to Golang.
I need to pass a function with a pointer receiver as an argument to a method, and to store that function pointer in other structs, etc.
Without a receiver, this is straightforward. For a function such as...
func Sample(ctx *Context, arg int) (err error)
...I can create a function type by using the syntax...
type SampleFunc func (ctx *Context, arg int) (err error)
...but for a function with a receiver such as...
func (ctx *Context) Sample(arg int) (err error)
...what's the syntax for the type definition? I tried...
type SampleFunc func (ctx *Context) (arg int) (err error)
...but that just yields syntax error: unexpected ( after top level declaration
Thanks for your advice.
The syntax is
type SampleFunc func (ctx *Context, arg int) (err error)
Assign the Sample
method to a variable of type SampleFunc
like this:
var f SampleFunc = (*Context).Sample
The (*)
part is required for pointer receiver methods. Call it like this:
f(ctx, 1)