Go Method Map

I have several methods that I call for some cases (e.g. Add, Delete, etc.). However, over time, the number of cases increases, and my switch cabinet becomes longer. Therefore, I decided to create a method map, for example, Go to the function map ; here the mapping of functions is trivial. However, is it possible to create a method map in Go?

When we have a method:

func (f *Foo) Add(a string, b int) { } 

The syntax below creates a compile-time error:

 actions := map[string]func(a, b){ "add": f.Add(a,b), } 

Can I create a method map in Go?

+4
source share
2 answers

Yes. Currently:

 actions := map[string]func(a string, b int){ "add": func(a string, b int) { f.Add(a, b) }, } 

Later: see go11func document guelfi document.

+8
source

There is currently no way to save both the receiver and the method in the same value (unless you store it in a structure). This currently works, and this may change with Go 1.1 (see http://golang.org/s/go11func ).

However, you can assign a method to a function value (without a receiver) and pass the value to the receiver later:

 package main import "fmt" type Foo struct { n int } func (f *Foo) Bar(m int) int { return fn + m } func main() { foo := &Foo{2} f := (*Foo).Bar fmt.Printf("%T\n", f) fmt.Println(f(foo, 42)) } 

This value can be stored on the map, like everything else.

+2
source

All Articles