Essential Go Maps  Edit on GitHub      File Issue

Zero value of a map

The zero value of a map is nil and has a length of 0.

var m map[string]string
fmt.Printf("m == nil ? %v\n", m == nil)
fmt.Printf("len(m) = %d\n", len(m))
m == nil ? true
len(m) = 0

A nil map has no keys nor can keys be added. A nil map behaves like an empty map if read from, but causes a runtime panic if written to.

var m map[string]string

// you can read read from un-initialized map
fmt.Printf(`m["foo"] = %s`+"\n", m["foo"])
_, ok := m["foo"]
fmt.Printf("ok: %v\n", ok)

// writing to uninitialized map panics
m["foo"] = "bar"
m["foo"] = 
ok: false
panic: assignment to entry in nil map

goroutine 1 [running]:
main.main()
	/books/go/0090-maps/zero_value2.go:15 +0x189
exit status 2

You should not read from or write to a zero value map.

  ↑ ↓ to navigate     ↵ to select     Esc to close