Can Functions Be Used as Keys in Go Maps?

Susan Sarandon
Release: 2024-11-01 04:10:02
Original
696 people have browsed it

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
}
Copy after login

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.
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!