Map#

map[K]V is a type.

eg.

var m map[string][]string

Nil vs Empty Map#

Nil Map#

eg.

var m map[string]int
fmt.Println(m == nil) // true

Empty Map#

eg.

m := map[string]int{}
fmt.Println(m == nil) // false

m2 := make(map[string]int)
fmt.Println(m2 == nil) // false

Initialization with make#

Maps created with make still have a length of 0, and they can grow past the initially specified size.

eg.

m := make(map[string]int, 10)
fmt.Println(len(m)) // 0
m["age"] = 10 // okay, without panic

Differences#

  • nil map: No memory allocation, JSON encodes to null.
  • Empty map: Memory allocated for header, JSON encodes to {}.

Operations on Nil Map#

Write (Panic)#

Writing to a nil map causes a panic.

eg.

var m map[string]int
m["key"] = 1 // panic: assignment to entry in nil map

Read#

Reading from a nil map returns the zero value of the value type.

eg.

var m map[string]int
v := m["key"]
fmt.Println(v) // 0

Delete#

delete on a nil map is a safe no-op.

eg.

var m map[string]int
delete(m, "key") // safe

Len#

len on a nil map returns 0.

eg.

var m map[string]int
fmt.Println(len(m)) // 0

# go