luminyra
使用指南

切片、集合与映射

给订单分组和分批,变换映射的值,并比较两个时间段的集合。

分组与分批

GroupBy 生成以客户为键的映射,Partition 按是否已付款拆成两组。映射的遍历顺序不固定,示例用 maps.Keys 及 slices.Sorted 得到稳定顺序。

coll/examples/slices/main.go
// GroupBy returns a map, whose iteration order is unspecified; sort the
// keys for stable output.
byCustomer := coll.GroupBy(orders, func(o order) string { return o.Customer })
for _, name := range slices.Sorted(maps.Keys(byCustomer)) {
	fmt.Printf("%s: %d orders\n", name, len(byCustomer[name]))
}

settled, pending := coll.Partition(orders, isPaid)
fmt.Printf("%d paid, %d pending\n", len(settled), len(pending))
在 GitHub 查看

已有订单编号切片时,用标准库 slices.Chunk 生成批次。

coll/examples/slices/main.go
// For a slice that is already in memory, the standard slices.Chunk
// batches it without copying.
for batch := range slices.Chunk(ids, 2) {
	fmt.Println("batch:", batch)
}
在 GitHub 查看

变换映射的值

先用标准库 maps.Clone 复制库存映射,再用 maps.DeleteFunc 移除缺货项。MapValues 保留键,把数量变成可读标签。

coll/examples/maps-sets/main.go
// Filtering a map is covered by the standard library: clone it, then
// remove entries with maps.DeleteFunc.
inStock := maps.Clone(stock)
maps.DeleteFunc(inStock, func(_ string, n int) bool { return n == 0 })

// MapValues passes only the value to the callback and keeps the keys.
labels := coll.MapValues(inStock, func(n int) string { return fmt.Sprintf("%d in stock", n) })
在 GitHub 查看

比较两个集合

Intersect 找到两个时间段都存在的成员,Difference 的输入顺序决定计算流失还是新增,Union 按首次出现的顺序合并并去重。

coll/examples/maps-sets/main.go
lastWeek := []string{"alice", "bob", "carol", "bob"}
thisWeek := []string{"bob", "dave", "carol", "erin"}

retained := coll.Intersect(lastWeek, thisWeek) // active both weeks, deduplicated
churned := coll.Difference(lastWeek, thisWeek) // active last week only
joined := coll.Difference(thisWeek, lastWeek)  // new this week
everyone := coll.Union(lastWeek, thisWeek)     // everyone, in order of first appearance
在 GitHub 查看

本页目录