Home  >  Article  >  Backend Development  >  Why Can\'t Functions Be Used as Map Keys in Go?

Why Can\'t Functions Be Used as Map Keys in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-31 18:27:29539browse

Why Can't Functions Be Used as Map Keys in Go?

Function Keys in Maps

This article explores the limitation of using functions as map keys in the Go programming language.

The Problem

Consider the following hypothetical Go code:

type Action func(int)
func test(a int) { }
func test2(a int) { }

func main() {
  x := map[Action]bool{}
  x[test] = true
  x[test2] = false
}

If you attempt to compile this code, you will encounter an error indicating that "invalid map key type Action."

The Answer

The Go language specification explicitly prohibits the use of functions, maps, and slices as map keys. Specifically, the specification states:

"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."

This restriction is in place because the equality comparison operators (== and !=) must be well-defined for the key type. Functions, maps, and slices are not suitable key types because their equality comparison is not fully defined.

Conclusion

While it may be tempting to use functions as map keys, it is not allowed in Go due to the need for well-defined equality comparisons. Therefore, you should use other suitable types, such as strings, integers, or structs, as map keys.

The above is the detailed content of Why Can\'t Functions Be Used as Map Keys in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn