Go

Why won't m["a"].count++ compile, and what happens with a nil map?

Question 493MediumGo 1.22 to 1.25
type stat struct{ count int }

m := map[string]stat{"a": {}}
m["a"].count++ // compile error: cannot assign to struct field m["a"].count in map

var nm map[string]int
fmt.Println(nm["x"], len(nm)) // 0 0, reads are fine
nm["x"] = 1                   // panic: assignment to entry in nil map

Map elements are not addressable. The runtime may move entries when the map grows, so Go does not let you change a field in place. Choose one fix:

s := m["a"]
s.count++
m["a"] = s                 // read, modify, write back

pm := map[string]*stat{"a": {}}
pm["a"].count++            // OK: the pointer is copied, the struct is shared

A nil map works for reads, len, delete, and range, but writing to it panics. The usual cause is a struct with a map field that was never initialized (type Cache struct{ m map[string]int } used without a constructor). Compare with nil slices, where append works fine. The interviewer wants the reason (addressability and growth) as well as the fixes.

More on Tricky Output & Code-Review Puzzles

All 38 Tricky Output & Code-Review Puzzles questions