Maps Collect Builds A New Map

Build a fresh map from a filtered iter.Seq2 with maps.Collect while the source map stays untouched throughout the rebuild.

GoData Integrity

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	quotas := map[string]int{
		"orders":  3,
		"billing": 1,
		"auth":    9,
		"search":  0,
	}

	// maps.Collect builds a brand-new map from the pairs the generator yields
	active := maps.Collect(func(yield func(string, int) bool) {
		for name, workers := range quotas {
			if workers > 0 && !yield(name, workers) {
				return
			}
		}
	})

	fmt.Println("source len:", len(quotas), "active len:", len(active))
	for _, name := range slices.Sorted(maps.Keys(active)) {
		fmt.Printf("active: %s=%d\n", name, active[name])
	}
}

The shape of this run

Maps Collect Builds A New Map is built around the function main.

The loop for name, workers := range quotas is the only repeated construct.

Using it

Output lines are prefixed (source len:, active:), so every printed line stays tied to the step behind it.

Key statements

active := maps.Collect(func(yield func(string, int) bool) {
	for name, workers := range quotas {
		if workers > 0 && !yield(name, workers) {
			return
		}
	}
})
for _, name := range slices.Sorted(maps.Keys(active)) {
	fmt.Printf("active: %s=%d\n", name, active[name])
}

Interactive Tools for This Topic

FAQ

What does Maps Collect Builds A New Map print when run?
Run it as a complete program — the output lines carry labels such as `source len:`, `active:`.