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.
Code
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
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
- How do you run Maps Insert Consumes Key Value Pairs?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.