Middle+
What keys can a map in Go have?
sobes.tech AI
Answer from AI
In Go, map keys can only be of types that support the comparison operation (operator ==). This means that keys must be comparable.
Suitable key types:
- Basic types: bool, int, float, string, etc.
- Pointers
- Structs, if all their fields are comparable
- Interfaces, if the concrete values inside are comparable
Keys that cannot be used:
- Slices
- Maps
- Functions
Example:
m := make(map[string]int) // string is a valid key
// Struct with comparable fields
type Point struct {
X, Y int
}
m2 := make(map[Point]string)
// Cannot use a slice
// m3 := make(map[[]int]string) // compilation error
This is because keys must have a defined and stable behavior when compared for the hash table to work correctly.