thecodex.expert · The Codex Family of Knowledge
Go

Maps

Go randomizes map iteration order on purpose, specifically so code never accidentally comes to depend on an order the language never promised.

Go 1.26 Order is randomized Last verified:
Canonical Definition

A map is Go’s built-in hash table type, written map[KeyType]ValueType. Keys must be a comparable type (numbers, strings, structs of comparable fields, and so on) — slices, maps, and functions cannot be keys because Go cannot compare them for equality. Iterating a map with range visits entries in an order that is deliberately randomized each run, specifically to stop code from ever relying on an order the language never guaranteed.

Creating and using maps

Maps are created with a literal or make, and support indexing, assignment, and delete:

Gomaps.go
ages := map[string]int{"Alice": 30, "Bob": 25}   // map literal
ages["Carol"] = 28                                 // add/update a key
delete(ages, "Bob")                                // remove a key

fmt.Println(ages["Alice"])   // 30
fmt.Println(ages["Dave"])    // 0 — zero value, NOT an error

The comma-ok idiom: telling "missing" from "zero"

Indexing a map for a missing key returns the value type's zero value, not an error — which is ambiguous if 0 or "" is also a valid stored value. The two-value form of a map read solves this: the second value is a bool reporting whether the key actually existed.

Gocomma_ok.go
value, ok := ages["Dave"]
if !ok {
    fmt.Println("Dave is not in the map")   // this runs: ok is false
} else {
    fmt.Println("Dave is", value)
}

nil maps: readable, but panic on write

A map variable's zero value is nil, not an empty map. Reading from a nil map is safe and behaves like an empty map (returns the zero value), but writing to a nil map causes a runtime panic. A map must be initialized with make or a literal before you write to it.

Gonil_maps.go
var m map[string]int      // nil map, not initialized
fmt.Println(m["x"])       // 0 — reading a nil map is safe

m["x"] = 1                // PANIC: assignment to entry in nil map

m = make(map[string]int)  // now it's safe to write
m["x"] = 1                // fine

Sources

1
The Go Authors. "Go maps in action", go.dev/blog/maps — the official blog post covering map semantics in depth.