Prune Map Entries With maps.DeleteFunc

Drop every entry failing a predicate in one pass with maps.DeleteFunc instead of collecting keys and deleting them in a second loop.

GoData Integrity

Code

gosnippet
26 lines
package main

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

func main() {
	cache := map[string]int{
		"users":    512,
		"sessions": 64,
		"audit":    4096,
		"tmp":      8,
	}

	// 一次遍历按条件删除:键与值都进谓词,删完无需重建
	maps.DeleteFunc(cache, func(key string, size int) bool {
		return size < 128
	})

	// 打印前排序键,输出逐次一致
	for _, key := range slices.Sorted(maps.Keys(cache)) {
		fmt.Printf("%s=%d\n", key, cache[key])
	}
}

One-pass deletion

maps.DeleteFunc(cache, predicate) walks the map once and deletes every entry whose predicate returns true. Here the predicate keeps only sizes >= 128, so tmp (8) and sessions (64) are dropped while users (512) and audit (4096) survive.

Deterministic printing

Map iteration order is random, so the printing loop sorts keys first with slices.Sorted(maps.Keys(cache)) and formats each surviving entry as key=value on its own line — the output is identical on every run.

Why not two loops

Collecting keys then deleting them needs a second pass and an intermediate slice; DeleteFunc folds both steps into one call and needs no extra allocation for the key list.

Interactive Tools for This Topic

FAQ

Why sort the keys before printing?
Go map iteration order is intentionally randomized; slices.Sorted(maps.Keys(cache)) makes the printed result identical across runs.
Does DeleteFunc allocate a key list?
No. The predicate runs inside a single pass over the map, so there is no intermediate slice of keys to collect and delete later.