Junior — Middle
What are the properties and requirements for keys in a map data structure?
sobes.tech AI
Answer from AI
In Go, keys in a map data structure must meet the following requirements:
- Keys must be comparable. This means the key type must support the comparison operations
==and!=. For example, basic types (int, string, bool), pointers, and interfaces with comparable values are suitable. - Slices, maps, and functions cannot be used as keys because they are not comparable.
Example of creating a map with string keys:
m := make(map[string]int)
m["one"] = 1
m["two"] = 2
Trying to use an incomparable type, such as a slice, will result in a compile-time error:
var s []int
m := make(map[[]int]string) // error: invalid map key type []int
Therefore, keys must be of types that can be compared for the map to work correctly.