Table of contents
Part of nurago, a collection of independent Go packages for backend services.
import "github.com/tecnickcom/nurago/pkg/maputil"
Package maputil filters, maps, reduces, and inverts Go maps with generic functions.
It offers a small set of generic, allocation-conscious helpers:
Filterkeeps entries matching a predicate.Maptransforms key/value pairs into a new map type.Reducefolds all entries into a single accumulator value.Invertswaps keys and values.
All functions are pure map-to-map/map-to-value transforms: they return new results and never mutate the input map directly.
Important Semantics
Go map iteration order is intentionally randomized. Therefore:
Reduceresults are deterministic only when the reducing function is order-independent (for example, commutative/associative operations).MapandInvertfollow “last write wins” semantics when multiple input entries map to the same output key.
When To Use
- You transform, filter, or invert maps regularly.
- You want the operation expressed once rather than as a loop at each call site.
Example
m := map[int]string{0: "Hello", 1: "World"}
filterFn := func(_ int, v string) bool { return v == "World" }
s2 := maputil.Filter(m, filterFn)
fmt.Println(s2)
// Output:
// map[1:World]
Full source is in example_maputil_test.go. More runnable examples are on pkg.go.dev.
Dependencies
This package reaches no external module: it uses only the Go standard library.