Batching Slices in Go Without Manual Indexes: The slices.Chunk IteratorBrief · digest for December 3
Brief≈ 1 min

Batching Slices in Go Without Manual Indexes: The slices.Chunk Iterator

For batch database inserts or API requests in Go, you used to write an i += n loop and clamp the right bound on the final chunk. Since Go 1.23, slices.Chunk in the standard library handles it cleanly:

// Split users slice into batches of 500 without manual indexing
for batch := range slices.Chunk(users, 500) {
    // Returning on error stops early without slicing the tail
    if err := saveBatch(batch); err != nil {
        return err
    }
}

Chunk[Slice ~[]E, E any](s Slice, n int) iter.Seq[Slice] returns a lazy iter.Seq iterator: no slice-of-slices is allocated upfront, and chunks yield one by one. On 1,200 items with n = 500, you get chunks of 500, 500, and 200; an empty slice yields zero iterations.

Keep two production gotchas in mind. First, shared memory: each batch views the backing array of users, so mutating elements edits the original slice (use slices.Clone(batch) before passing to goroutines). Thankfully, sub-slice capacity cap is clipped to its length, so append won't overwrite the next batch. Second, n < 1: passing zero or a negative size panics right away, even on an empty slice. Validate batch size before looping.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 7