Junior — Middle
What data types are allowed as keys in a map structure?
sobes.tech AI
Answer from AI
In Go, the keys for a map can only be of types that support the comparison operation (comparable). This means that keys can be:
- Boolean values (bool)
- Numbers (int, float, complex, etc.)
- Strings (string)
- Pointers
- Interfaces, if the dynamic type supports comparison
- Structs, if all their fields are comparable
Slices, maps, functions, and other non-comparable types cannot be used as keys because they do not support the == operator.
Example:
m := make(map[string]int)
m["key"] = 42
// Struct with comparable fields
type Point struct {
X, Y int
}
m2 := make(map[Point]string)
m2[Point{1,2}] = "A point"