Maps

Contents

Maps#

A map is an unordered key-value container. Keys can be any comparable type (anything that supports ==).

Literal form.

m := map[string]int{"a": 1, "b": 2}

Insert or update.

m["c"] = 3

Comma-ok lookup distinguishes “missing” from “zero”.

v, ok := m["a"]              // v=1, ok=true
_, ok := m["x"]              // ok=false

Delete an entry.

delete(m, "a")

Iterate; the iteration order is randomised.

for k, v := range m {
    fmt.Println(k, v)
}

A nil map allows reads (returns the zero value) but panics on write. The operator creates with make or a literal.

References#