Range over Iterators
Since Go 1.23, range can iterate over functions that yield values; iterators must stop when yield returns false.
Since Go 1.23, range can read values from a function. An iter.Seq[V] is an iterator, a function that produces values one at a time. It calls yield to hand each value to the ordinary range loop.
When the loop stops early, yield returns false to tell the iterator that no more values are wanted. The iterator must then return instead of producing more.
package main
import (
"fmt"
"iter"
)
func Count(n int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := 0; i < n; i++ {
if !yield(i) {
return
}
}
}
}
func main() {
for n := range Count(5) {
if n == 3 {
break
}
fmt.Println(n)
}
}In production
An iterator can produce values without first storing all of them in a slice. This is useful for large inputs or values read from a stream. This feature and Go's iter package require Go 1.23 or later. Stop producing values when yield returns false.
Enjoyed this? Get more software craft delivered to your inbox.