Junior — Middle
What types of data are suitable for use as keys in a Map structure?
sobes.tech AI
Answer from AI
In Go, the keys in a map structure can only be of types that support comparison operations for equality (== and !=). This is because, to find a value by key, the keys need to be compared.
Suitable key types:
- Basic types:
int,float64,string,bool, etc. - Pointers
- Structs, if all their fields are comparable
- Arrays, if elements are comparable
Cannot be used as keys:
- Slices (
slice) - Maps (
map) - Functions
Example usage:
m := make(map[string]int)
m["apple"] = 5
m["banana"] = 3
fmt.Println(m["apple"]) // 5
Trying to use a slice as a key will result in a compile-time error.