Junior — Middle
What types of keys are allowed for use in a Map data structure?
sobes.tech AI
Answer from AI
In Go, keys for data structures like map must be of comparable types, meaning types that can be used with == and != operators.
Valid key types include:
- Primitive types:
int,float64,string,bool, etc. - Pointers
- Structs, if all their fields are comparable
- Arrays, if their elements are comparable
Invalid key types include:
- Slices (
[]) - Maps (
map) - Functions
Example of using a map with string keys:
m := make(map[string]int)
m["apple"] = 5
fmt.Println(m["apple"]) // 5
Attempting to use a slice as a key will result in a compile-time error.