Map#
map[K]V is a type.
eg.
var m map[string][]stringNil vs Empty Map#
Nil Map#
eg.
var m map[string]int
fmt.Println(m == nil) // trueEmpty Map#
eg.
m := map[string]int{}
fmt.Println(m == nil) // false
m2 := make(map[string]int)
fmt.Println(m2 == nil) // falseInitialization 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 panicDifferences#
nilmap: No memory allocation, JSON encodes tonull.- 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 mapRead#
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) // 0Delete#
delete on a nil map is a safe no-op.
eg.
var m map[string]int
delete(m, "key") // safeLen#
len on a nil map returns 0.
eg.
var m map[string]int
fmt.Println(len(m)) // 0