Home > Article > Backend Development > Can Functions Be Used as Keys in Go Maps?
Mapping with Function Keys
Mapping data using functions as keys can provide flexibility in accessing values. However, attempting to create a map with a function as a key, as illustrated below, results in an error:
type Action func(int) func test(a int) { } func test2(a int) { } func main() { x := map[Action]bool{} x[test] = true x[test2] = false }
Error: invalid map key type Action
Language Restriction
The Go language specification explicitly states that functions cannot be used as map keys. This restriction stems from the requirement that keys must support operators like equality comparison, which is not possible for functions.
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.
Therefore, using functions as map keys is disallowed by the language to ensure the consistency of key comparisons and prevent potential errors.
The above is the detailed content of Can Functions Be Used as Keys in Go Maps?. For more information, please follow other related articles on the PHP Chinese website!