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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.