Senior
What data type can be a key in a dictionary?
sobes.tech AI
Answer from AI
In a dictionary (map), the key can be any data type that is comparable in the programming language, meaning it supports equality comparison operations.
In different languages, this may imply different restrictions, but generally, keys can be:
- Primitive types: strings, numbers, boolean values
- Tuples or structures, if all their fields are comparable
- Pointers
In Go, for example, a map key can be any type that can be compared using the == operator, so slices, maps, and functions cannot be keys because they are not comparable.
Example in Go:
m := make(map[string]int)
m["key"] = 42
// Structure with comparable fields
type Point struct {
X, Y int
}
m2 := make(map[Point]string)
m2[Point{1,2}] = "A"
Thus, keys must be of immutable and comparable types.