You cannot do this directly, as already mentioned, but you can fake it like this:
package main import "fmt" func a(i int) int { return i + 1 } func b(i int) int { return i + 2 } type Function func(int)int type FunctionWrapper struct { f *Function } var fnMap = make(map[string]FunctionWrapper) // MakeFunctionWrapper returns a unique FunctionWrapper per Function pointer, using fnMap to avoid having multiple values for the same function func MakeFunctionWrapper(f Function) FunctionWrapper { key := fmt.Sprintf("%#v", f) data, ok := fnMap[key] if !ok { data = FunctionWrapper{&f} fnMap[key] = data } return data } func main() { functions := make(map[FunctionWrapper]bool) fa := MakeFunctionWrapper(a) fb := MakeFunctionWrapper(b) fb2 := MakeFunctionWrapper(b) functions[fa] = true functions[fb] = true functions[fb2] = false // This overwrites the previous value since fb is essentially the same as fb2 fmt.Println(functions[fa]) // "true" fmt.Println(functions[fb]) // "false" fmt.Println(functions[fb2]) // "false" }
Check it out on the Go Playground
This is a bit cumbersome, and I honestly think that it is a very bad idea to essentially use a string version of the pointer as the map key. But ... this is at least an option if you really need it.
source share