How to use function as map's key

You cannot use a function as a map key. The language specification clearly says:

The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice.


You can't use functions as keys in maps : the key type must be comparable.

From Go blog :

map keys may be of any type that is comparable. The language spec defines this precisely, but in short, comparable types are boolean, numeric, string, pointer, channel, and interface types, and structs or arrays that contain only those types. Notably absent from the list are slices, maps, and functions; these types cannot be compared using ==, and may not be used as map key

What you might use, depending on your precise use case, is an interface.


While functions can't be keys, function pointers can.

package main

import "fmt"

type strFunc *func() string

func main() {

    myFunc := func() string { return "bar" }
    m := make(map[strFunc]string)
    m[(strFunc)(&myFunc)] = "f"

    for f, name := range m {
        fmt.Println((*f)(), name)
    }
}

http://play.golang.org/p/9DdhYduX7E