maputil

maputil filters, maps, reduces, and inverts Go maps with generic functions.

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:

  • Filter keeps entries matching a predicate.
  • Map transforms key/value pairs into a new map type.
  • Reduce folds all entries into a single accumulator value.
  • Invert swaps 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:

  • Reduce results are deterministic only when the reducing function is order-independent (for example, commutative/associative operations).
  • Map and Invert follow “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.