Junior — Middle
Can you describe the main characteristics and features of using keys in data structures like Map?
sobes.tech AI
Answer from AI
In the Go (Golang) language, map is a built-in data type representing an associative array or dictionary that stores key-value pairs.
Main characteristics of keys in a map:
- Key type must be comparable: keys must support the
==comparison operation. This means keys can be types like strings, numbers, pointers, structs, as long as all their fields are comparable. - Slices, maps, or functions cannot be used as keys because they are not comparable.
- Keys are unique: a map cannot have two identical keys.
Example of creating and using a map with string keys:
package main
import "fmt"
func main() {
m := make(map[string]int)
m["apple"] = 5
m["banana"] = 3
fmt.Println(m["apple"]) // Outputs 5
// Checking for key existence
val, ok := m["pear"]
if !ok {
fmt.Println("Key 'pear' not found")
} else {
fmt.Println(val)
}
}
Thus, when using keys in a map, it is important to choose types that support comparison to avoid compilation errors.