Senior
What data types can be used as keys in a map?
sobes.tech AI
Answer from AI
In Go, map keys can only be types that support comparison operations for equality (== and !=). This is because maps use hashing and key comparison to find values.
Suitable key types:
- Boolean values (bool)
- Numbers (int, float64, uint, etc.)
- Strings (string)
- Pointers
- Channels
- Interfaces, if the dynamic type of the key supports comparison
- Structs, if all their fields are comparable
Cannot be used:
- Slices
- Maps
- Functions
Example of using a map with a struct type as a key:
package main
import "fmt"
type Point struct {
X, Y int
}
func main() {
m := make(map[Point]string)
m[Point{1, 2}] = "A"
fmt.Println(m[Point{1, 2}]) // Will print "A"
}
Attempting to use a non-comparable type as a key will result in a compile-time error.