Range-Over-Function
Start with Range-Over-Function
Go 1.23 allows a for-range loop to consume specially shaped iterator functions.
What you’ll learn
- Explain the main purpose of range-over-function.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
An iterator yielding one value has a signature compatible with func(yield func(V) bool). A two-value iterator uses func(yield func(K, V) bool). When the loop body uses break, the compiler makes the yield callback return false to the producer.
The producer must stop calling yield after false is returned. Understanding this contract makes it easier to write adapters without leaking resources or continuing work after a consumer stops.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Requires Go 1.23 or later. See the Go 1.23 release notes.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func pairs(yield func(int, string) bool) {
for i, name := range []string{"red", "blue", "green"} {
if !yield(i, name) {
return
}
}
}
func main() {
for index, name := range pairs {
fmt.Println(index, name)
if index == 1 {
break
}
}
}
Output
0 red
1 blueTrace what the program does
The loop sees index 0 red and index 1 blue, then breaks. The yield callback returns false, causing pairs to return before yielding green.
Avoid common mistakes
- A producer must respect yield=false after the consumer breaks.
- Range-over-function became available in Go 1.23; older compilers cannot compile this syntax.
Try it yourself
Update the loop to stop after printing only the first item and predict the output.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Range-Over-Function in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.