Use iterator functions and range-over-function
Use iterator functions and range-over-function
Go 1.23 introduced range over iterator functions. A one-value iterator has signature func(yield func(T) bool); it calls yield for each element. The compiler supplies yield for the loop body. If yield returns false, the iterator must stop calling it. Two-value iterators use func(yield func(K,V) bool); zero-value iterators use func(yield func() bool).
package main
import ( "fmt")
func odds(yield func(int) bool) { for i := 1; i <= 7; i += 2 { if !yield(i) { return } }}func main() { for n := range odds { fmt.Println(n) if n == 3 { break } }}Breaking the loop makes yield return false. odds observes that return and exits. Do not continue yielding afterward. This code requires Go 1.23 language semantics, not just a compiler that recognizes the syntax.
Expected output:
13Yield index and value
package main
import ( "fmt")
func entries(s []string) func(func(int, string) bool) { return func(yield func(int, string) bool) { for i, v := range s { if !yield(i, v) { return } } }}func main() { for i, v := range entries([]string{"tea", "rice"}) { fmt.Println(i, v) }}The closure returns an iterator with two iteration values. Each invocation traverses the captured slice; it does not create a snapshot. The standard iter package names these shapes Seq and Seq2. Do not assume every iterator is repeatable; check its contract. No goroutine or channel is needed here.
Expected output:
0 tea1 riceTry it locally
Write a one-value iterator yielding 2, 4 and 6. Range over it and print the running sum after the loop. Stop yielding if the callback returns false.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced type semantics 07: Use iterator functions and range-over-function
Check the lesson objective before moving on.
Which language version introduced range over functions?
What must an iterator do when yield returns false?