What Are Range-Over-Function Iterators in Go (Go 1.23+)

Range-over-function iterators in Go 1.23+ enable custom iteration by passing a yield-based function directly to a range loop.

Range-over-function iterators in Go 1.23+ allow you to iterate over custom sequences by passing a function that yields values to a range loop. You define a function that accepts a yield callback and call it inside the range statement to process each yielded item.

func CountTo(n int) func(func(int) bool) {
	return func(yield func(int) bool) {
		for i := 1; i <= n; i++ {
			if !yield(i) {
				return
			}
		}
	}
}

for v := range CountTo(5) {
	fmt.Println(v)
}