With Method Values
You may use Method values for this purpose. A method value is a function value with implicit receiver. Quoting from Spec: Method values:
If the expression x
has static type T
and M
is in the method set of type T
, x.M
is called a method value.
So the syntax for a method value is x.M
, where for example x
is a value of the type, M
is the name of the method. This results in a function with the same parameters (and return types) as the method without a receiver, as the receiver will be saved with the method value and will be implicit.
So this means to store method values for your doSometing()
and doAnotherThing()
methods, the function type will simply be func (int)
(no receiver).
Here's a working example:
type mystruct struct {
name string
}
func (my *mystruct) doA(i int) {
fmt.Printf("[doA]: I'm %s, param is: %d\n", my.name, i)
}
func (my *mystruct) doB(i int) {
fmt.Printf("[doB]: I'm %s, param is: %d\n", my.name, i)
}
func main() {
my1 := &mystruct{"Bob"}
my2 := &mystruct{"Alice"}
lookupMap := map[string]func(int){
"action1": my1.doA,
"action2": my2.doB,
}
lookupMap["action1"](11)
lookupMap["action2"](22)
}
Output (try it on the Go Playground):
[doA]: I'm Bob, param is: 11
[doB]: I'm Alice, param is: 22
With Method Expressions
If you don't want the receiver saved in the dictionary (within the method values), you can go along with the Method expressions.
The difference is that when you obtain a function value, you don't use x.M
but T.M
, which will result in a function value, with a function type having the same parameters (and return types), but the receiver type will also be in the parameter list, and in the first place. See quote from Spec: Method expressions:
If M
is in the method set of type T
, T.M
is a function that is callable as a regular function with the same arguments as M
prefixed by an additional argument that is the receiver of the method.
So the function type to work with will look like this in your case: func(*mystruct, int)
Also, since the receiver will not be saved, you have to provide it when calling these functions.
See this working example (which is the modification of the first example):
type mystruct struct {
name string
}
func (my *mystruct) doA(i int) {
fmt.Printf("[doA]: I'm %s, param is: %d\n", my.name, i)
}
func (my *mystruct) doB(i int) {
fmt.Printf("[doB]: I'm %s, param is: %d\n", my.name, i)
}
func main() {
lookupMap := map[string]func(*mystruct, int){
"action1": (*mystruct).doA,
"action2": (*mystruct).doB,
}
my1 := &mystruct{"Bob"}
my2 := &mystruct{"Alice"}
lookupMap["action1"](my1, 11)
lookupMap["action2"](my2, 22)
}
Output is the same (try it on the Go Playground):
[doA]: I'm Bob, param is: 11
[doB]: I'm Alice, param is: 22
See similar questions:
golang - pass method to function
golang function alias on method receiver