Explain nil map behavior
Explain nil map behavior
The zero value of a map is nil. A nil map can be read, ranged over, measured with len, cleared or passed to delete. It has no entries. Assigning an element into a nil map panics at runtime, so initialize it first.
package main
import "fmt"
func main() { var m map[string]int v, ok := m["tea"] delete(m, "tea") clear(m) n := 0 for range m { n++ } fmt.Println(m == nil, len(m), v, ok, n)}No iteration occurs and the read is safe. Checking len(m) == 0 detects both nil and empty maps; m == nil distinguishes an uninitialized map. Do not use a write as a nil check.
Expected output:
true 0 0 false 0Initialize before writing
package main
import "fmt"
func put(m map[string]int, k string, v int) map[string]int { if m == nil { m = make(map[string]int) } m[k] = v return m}func main() { var m map[string]int m = put(m, "tea", 2) m = put(m, "rice", 4) fmt.Println(m == nil, m["tea"], m["rice"])}The function allocates only when needed and returns the usable map. Assigning a new map to a parameter does not replace the caller variable, so retain the return value.
Expected output:
false 2 4Try it locally
Declare a nil map, print its length and nil check, initialize it, store x=9 and print the value and nil check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maps 04: Explain nil map behavior
Check the lesson objective before moving on.
Which operation panics on a nil map?
Can a nil map be ranged over?