Junior — Middle
What are the main features and types of keys in a map data structure?
sobes.tech AI
Answer from AI
In Go, the data structure map represents an associative array or dictionary that maps keys to values.
Main features of keys in a map:
- Keys must be of a comparable type, meaning they can be used with the
==operator. This includes basic types (int, string, bool), pointers, interfaces, structs, and arrays if all their fields are comparable. - Slices, maps, or functions cannot be used as keys because they are not comparable.
Example of creating and using a map:
m := make(map[string]int)
m["apple"] = 5
m["banana"] = 3
fmt.Println(m["apple"]) // 5
Thus, the key type affects the usability of the map and should be chosen considering the comparability requirements.