← 中文资源

简体中文版本

maps.Collect 构建全新 map

maps.Collect 消费 iter.Seq2 直接构建出一个全新的 map:过滤逻辑写进生成器闭包,来源 map 在整个重建过程中原样不动。

阅读英文原文

实现说明

maps.Collect 构建全新 map可以归结为函数 main。 for name, workers := range quotas 反复执行,循环体之外没有别的重复。

使用要点

  • 演示输出是带标签的(source len:、active:),每个操作都会留下自己的一行标注。

常见问题

运行「maps.Collect 构建全新 map」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 source len:、active: 标签标明各步骤。

核心语句

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

代码示例

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