← 中文资源

简体中文版本

maps.Insert 消费键值对序列

maps.Insert 直接消费 iter.Seq2 键值对序列灌入 map:已有键覆盖、缺失键新建;配合闭包内联生成序列,省掉先攒切片再循环 insert 的样板。

阅读英文原文

实现说明

maps.Insert 消费键值对序列以函数 main为骨架。 这个示例中仅有的重复出现在 for _, item := range raw 里。

常见问题

「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
		}
	}
})
for _, key := range slices.Sorted(maps.Keys(quota)) {
	fmt.Printf("%s=%d\n", key, quota[key])
}
quota := make(map[string]int, len(raw))

代码示例

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])
	}
}