Mutations
Managing data within a map involves four primary operations.
Insert and Update
Adding or overwriting an element is done using the index operator.
m[key] = value
Get an Element
Retrieving a value is straightforward. If the key doesn’t exist, it returns the zero value for the value type.
val := m[key]
Delete an Element
The built-in delete() function removes a key/value pair. It is safe to call even if the key doesn’t exist.
delete(m, "Alice")
Check If a Key Exists (The “Comma OK” Idiom)
To distinguish between a missing key and a key that actually contains a zero value, use the two-value assignment:
val, ok := m[key]
if ok {
// key exists, val is its value
} else {
// key does not exist, val is the zero value
}
Reference Behavior
Like slices, maps are reference types. If you pass a map to a function and modify it, the changes will be reflected in the original map.