How to use function as map's key? for example:
type Action func(int)
func test(a int) { }
func test2(a int) { }
func main() {
x := map[Action]bool{}
x[test] = true
x[test2] = false
}
those code would show an error: invalid map key type Action
You cannot do this directly, as mentioned already, but you can sort of fake it you do something like this:
Check it out on the Go playground
This is a bit cumbersome, and I honestly think it's a very bad idea to essentially use the string version of a pointer as your map's key. But ... it's at least an option if you really need it.
You can't use functions as keys in maps : the key type must be comparable.
From Go blog :
What you might use, depending on your precise use case, is an interface.
While functions can't be keys, function pointers can.
http://play.golang.org/p/9DdhYduX7E
You cannot use a function as a map key. The language specification clearly says:
You can use
reflect
.Functions cannot be keys:
Source