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
- Q491Code review: why does Counter always report 0, and what else is wrong?
- Q492What happens if you add or delete map entries while ranging over the map?
- Q494Spot the bug: why is err nil after the if block?
- Q495Find the two WaitGroup bugs.
- Q496Why does this loop spin at 100% CPU after one channel closes?
- Q497What does this select print, and where does the break go?