Go Reference ยท Concepts
Range-over-func iterators in Go
Learn Go 1.23 iterators: push iterators with iter.Seq and iter.Seq2, range over functions, early exit, pull iterators with iter.Pull, and the standard library helpers.
Since Go 1.23 a for range loop can iterate over a function. An iterator is a function that takes a yield callback and calls it once for each element; the loop body becomes that callback. The iter package names the two shapes: iter.Seq[V] yields single values and iter.Seq2[K, V] yields pairs.
This is a push iterator: the iterator drives, calling your loop body. When you need to drive instead (to walk two sequences in step, say), iter.Pull converts a push iterator into a pull iterator with next and stop functions.
func Count(n int) iter.Seq[int] { return func(yield func(int) bool) { for i := 0; i < n; i++ { if !yield(i) { return } } } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Usage notes
- Always check the return value of
yield. If the loop body breaks, returns or panics,yieldreturnsfalse. Callingyieldagain after that panics at run time. - Keep it lazy. An iterator does no work until ranged over, and each range starts afresh. This makes sequences composable (
Filter,Map,Take) without building slices. - Single use vs reusable. Most iterators can be ranged over repeatedly. If yours is single-use (reading a stream), say so in the doc comment.
- Standard helpers:
slices.Values,slices.All,slices.Backward,slices.Collect,slices.Sorted,maps.Keys,maps.Values,maps.All,strings.SplitSeqandstrings.Lines(Go 1.24),bytes.Lines. Methods namedAll,Keys,Valuesfollow the convention. iter.Pullcosts more: it runs the iterator on a coroutine. Always callstop(usedefer) so resources are released. Prefer push iterators unless you truly need lock-step control.deferin the loop body runs at the end of the enclosing function, not per iteration, exactly as in a normal loop, even though the body is a closure.goto, labels,break,continue,returnanddeferall work inside the body of a range-over-func loop; the compiler rewrites them.- Iterators can be generic, which makes them ideal for pipelines. Errors are usually exposed as a pair:
iter.Seq2[T, error].
Related
range,for,func,map, Generics rules- Lessons: Iterators, range, Slices and maps packages