Junior — Middle
What actions are permissible with a Map type variable that has not yet been initialized?
sobes.tech AI
Answer from AI
In Go, a variable of type map defaults to nil if it has not been initialized.
Actions permissible with a nil map include:
- Reading a value by key — returns the zero value of the value type and a flag indicating the key's absence.
- Checking for the presence of a key using the
value, ok := map[key]operator.
Actions that are not allowed:
- Writing (assigning a value to a key) will cause a panic.
- Calling functions that modify the map (e.g.,
delete) on anilmap is safe and does not cause a panic.
Example:
var m map[string]int // m == nil
v, ok := m["key"] // ok == false, v == 0
// m["key"] = 10 // panic: assignment to entry in nil map
delete(m, "key") // safe, does nothing
To use a map for writing, it needs to be initialized, for example, using make:
m = make(map[string]int)
m["key"] = 10 // now works