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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.RAG Document Chunk VisualizerSplit long documents into RAG chunks by character or word count with configurable overlap, boundary alignment, token stats, and highlighted overlaps.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.