Senior
What is a map in Go, how does it work, and what are its features?
sobes.tech AI
Answer from AI
In Go, a map is a built-in data type that implements an associative array or dictionary, where keys are mapped to values.
Features of map in Go:
- Keys can be of any type that supports comparison (e.g., strings, numbers, pointers).
- Values can be of any type.
- Can be initialized using
makeor a literal:
m := make(map[string]int)
m2 := map[string]int{"a": 1, "b": 2}
- Access to elements via
m[key], if the key is absent — the zero value of the type is returned. - Checking for the presence of a key:
val, ok := m["key"]
if ok {
// key exists
}
mapdoes not guarantee the order of traversal of elements.mapis not thread-safe; synchronization is needed for concurrent access.
Example:
m := make(map[string]int)
m["apple"] = 5
fmt.Println(m["apple"]) // 5
val, ok := m["banana"]
if !ok {
fmt.Println("banana not found")
}