← 中文资源

简体中文版本

slices.Chunk 定长分批遍历

slices.Chunk 以定长批次遍历切片:返回 iter.Seq,长度不整除时最后一批自动变短;批次与原切片共享底层数组,只读使用。

阅读英文原文

实现说明

slices.Chunk 定长分批遍历可以归结为函数 main。 这个示例中仅有的重复出现在 for batch := range slices.Chunk(ids, 3) 里。

使用要点

  • 跑完文件,输出里会留下标记——batch:、collected:、upload。

常见问题

运行「slices.Chunk 定长分批遍历」会打印什么?

整个文件跑完,输出行以 batch:、collected:、upload 这类前缀开头。

核心语句

for batch := range slices.Chunk(ids, 3) {
	fmt.Println("batch:", batch)
}
for i, batch := range batches {
	fmt.Printf("upload %d -> %d items starting at %d\n", i, len(batch), batch[0])
}

代码示例

package main

import (
	"fmt"
	"slices"
)

func main() {
	ids := []int{101, 102, 103, 104, 105, 106, 107}

	// slices.Chunk returns iter.Seq[[]E]: each range step yields one fixed-size batch
	for batch := range slices.Chunk(ids, 3) {
		fmt.Println("batch:", batch)
	}

	// 7 does not divide by 3: the last batch holds the remainder of 1
	batches := slices.Collect(slices.Chunk(ids, 3))
	fmt.Println("collected:", len(batches), "last size:", len(batches[len(batches)-1]))

	// Batches are adjacent sub-slices sharing ids' backing array: read-only use, never append into a batch
	for i, batch := range batches {
		fmt.Printf("upload %d -> %d items starting at %d\n", i, len(batch), batch[0])
	}
}