maps

Guided tour · Collections · pkg.go.dev →

Generic map operations (Go 1.21+). The missing helpers for Go's built-in map type.

Querying

Keys / Values — iterators (1.23+)

These now return iter.Seq, not a slice. Use slices.Collect if you need a slice.

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

for k := range maps.Keys(m) {
    fmt.Println(k)
}

keys := slices.Collect(maps.Keys(m))
slices.Sort(keys)   // map iteration order is random
fmt.Println(keys)

Equal

maps.Equal(
    map[string]int{"a": 1},
    map[string]int{"a": 1},
) // true

Mutation

Clone — shallow copy

m := map[string]int{"a": 1}
n := maps.Clone(m)
n["a"] = 99
fmt.Println(m["a"], n["a"])  // 1 99

Copy — merge into existing

Copy(dst, src) overwrites any shared keys in dst with src's values.

a := map[string]int{"x": 1, "y": 2}
b := map[string]int{"y": 20, "z": 30}
maps.Copy(a, b)
fmt.Println(a)  // map[x:1 y:20 z:30]

DeleteFunc — conditional delete

m := map[string]int{"a": 1, "b": -1, "c": 2}
maps.DeleteFunc(m, func(k string, v int) bool { return v < 0 })

Building maps from iterators

Collect — build a map from a Seq2

The inverse of maps.All. Handy when transforming a slice into a keyed lookup.

pairs := func(yield func(string, int) bool) {
    yield("a", 1)
    yield("b", 2)
}
m := maps.Collect(pairs)
fmt.Println(m)