Maps Insert Consumes Key Value Pairs

maps.Insert consumes an iter.Seq2 of key-value pairs straight into a map, overwriting existing keys, so loading data skips the collect-then-loop boilerplate.

GoData Integrity

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"maps"
	"slices"
	"strconv"
	"strings"
)

func main() {
	raw := []string{"orders=3", "billing=1", "auth=9", "orders=42"}

	quota := make(map[string]int, len(raw))
	// iter.Seq2 就是一个 yield 函数:maps.Insert 直接消费键值对序列
	maps.Insert(quota, func(yield func(string, int) bool) {
		for _, item := range raw {
			key, value, _ := strings.Cut(item, "=")
			n, _ := strconv.Atoi(value)
			if !yield(key, n) {
				return
			}
		}
	})

	// 重复键后写覆盖先写:orders 最终是 42
	for _, key := range slices.Sorted(maps.Keys(quota)) {
		fmt.Printf("%s=%d\n", key, quota[key])
	}
}

How the code behaves

Maps Insert Consumes Key Value Pairs comes down to the function main.

One loop does the cycling here: for _, item := range raw.

Iteration is driven by for _, item := range raw and for _, key := range slices.Sorted(maps.Keys(quota)).

Statements that matter

maps.Insert(quota, func(yield func(string, int) bool) {
	for _, item := range raw {
		key, value, _ := strings.Cut(item, "=")
		n, _ := strconv.Atoi(value)
		if !yield(key, n) {
			return
		}
	}
})
for _, key := range slices.Sorted(maps.Keys(quota)) {
	fmt.Printf("%s=%d\n", key, quota[key])
}
quota := make(map[string]int, len(raw))

Interactive Tools for This Topic

FAQ

How do you run Maps Insert Consumes Key Value Pairs?
Direct execution is enough; the script has no external requirements.