Standard library / slices

slices.Chunk()

Yields consecutive sub-slices of at most n elements, clipped so append cannot overwrite the next chunk. Shares existing elements; panics for n <= 0. Expected stdout: '[1 2] 2\n[3 4] 2\n[5] 1\n'.

Formal Syntax & Structure

go syntaxgo
func Chunk[Slice ~[]E, E any](s Slice, n int) iter.Seq[Slice]

Parameters & Attributes

NameTypeDescription
sSliceInput slice; may share its backing array.
nintCount or bound for this operation.

Return Value

iter.Seq[Slice]

Yields consecutive sub-slices of at most n elements, clipped so append cannot overwrite the next chunk. Shares existing elements; panics for n <= 0.

Working Example

Example Snippetgo
package main
import (  "fmt"  "slices")
func main() {  for c := range slices.Chunk([]int{1, 2, 3, 4, 5}, 2) {    fmt.Println(c, cap(c))  }}
Go Reference