slices.Chunk Splits Into Fixed Batches

slices.Chunk walks a slice in fixed-size batches through an iterator, yielding one shorter final batch when the length is not evenly divisible.

GoData Integrity

Code

gosnippet
24 lines
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])
	}
}

Line-by-line reading

slices.Chunk Splits Into Fixed Batches comes down to the function main.

A single loop drives the file — for batch := range slices.Chunk(ids, 3).

Applying it

Running the file prints labeled results such as batch:, collected:, upload — each operation’s effect is visible in the output.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does slices.Chunk Splits Into Fixed Batches print when run?
Execute the whole file; each printed line is prefixed with a label like `batch:`, `collected:`, `upload`.