HowtoGo
Home / Standard Library / The maps Package
Standard Library

The maps Package

maps is ten generic functions for the loops you would otherwise write by hand: copy a map, compare two, prune one, and walk one as a sequence of keys, values, or pairs.

Examples

Map order is random, so a stable listing goes through slices.Sorted.

func main() {
    stock := map[string]int{"washer": 0, "bolt": 12, "nut": 30}

    for _, name := range slices.Sorted(maps.Keys(stock)) {
        fmt.Printf("%-7s %d\n", name, stock[name])
    }

    total := 0
    for n := range maps.Values(stock) {
        total += n
    }
    fmt.Println("total:", total)
}
Output
bolt    12
nut     30
washer  0
total: 42

Maps and sequences

FunctionDescription
Keys[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[K]
for k := range maps.Keys(m)
A sequence of the map's keys.
Values[Map ~map[K]V, K comparable, V any](m Map) iter.Seq[V]
for v := range maps.Values(m)
A sequence of the map's values.
All[Map ~map[K]V, K comparable, V any](m Map) iter.Seq2[K, V]
maps.Insert(dst, maps.All(src))
A sequence of the map's key-value pairs.
Collect[K comparable, V any](seq iter.Seq2[K, V]) map[K]V
m := maps.Collect(seq)
Builds a new map from a sequence of pairs.
Insert[Map ~map[K]V, K comparable, V any](m Map, seq iter.Seq2[K, V])
maps.Insert(m, maps.All(other))
Adds a sequence of pairs into an existing map.

Whole-map operations

FunctionDescription
Clone[M ~map[K]V, K comparable, V any](m M) M
cfg := maps.Clone(defaults)
A new map with the same entries.
Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2)
maps.Copy(cfg, overrides)
Copies src's entries into dst.
Equal[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool
maps.Equal(got, want)
True when both hold the same keys and values.
EqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool
maps.EqualFunc(a, b, strings.EqualFold)
Equal, with your own comparison for the values.
DeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool)
maps.DeleteFunc(m, func(k string, v int) bool { return v == 0 })
Deletes every entry the function says yes to.