JuniorCodeCommonNot answered yet
What happens reading then writing a nil map?
A nil map is read from, then written to. State the exact effect of each line — whether it succeeds (and what value it yields) or panics (and with what message).
var m map[string]int
fmt.Println(m["x"]) // read
m["x"] = 1 // write
Predict the output.
The read m["x"] is fine and returns the zero value 0 — reading a nil map never panics. The write m["x"] = 1 panics with assignment to entry in nil map. You must initialize the map first with make(map[string]int) or a literal before writing to it.
- ✗Thinking reading a
nilmap panics — only writing does - ✗Expecting the write to lazily allocate the map like
appendgrows anilslice - ✗Forgetting that a map declared with
var m map[K]Visnil, not an empty map
- →Why can you
appendto anilslice but not write to anilmap? - →What does
len(m)return on anilmap, and does ranging over it panic?
Contents
What does this code print/do?
var m map[string]int
fmt.Println(m["x"]) // read
m["x"] = 1 // write
Result
0
panic: assignment to entry in nil map
Why
var m map[string]int declares a nil map — a header with no backing hash table.
- Reading a
nilmap is allowed: it never dereferences the table and simply returns the type's zero value (0forint). This makes "does the key exist" checks via comma-ok safe:v, ok := m["x"]gives0, false. - Writing needs a slot in the table, which does not exist, so the runtime panics:
assignment to entry in nil map.
The fix is to initialize the map before writing:
m := make(map[string]int) // or map[string]int{}
m["x"] = 1 // ok
⚠️ Unlike a nil slice, where append can allocate a backing array, a nil map is not auto-initialized on write.
Contents