Go 1.23 introduces range-over-function iterators, allowing you to iterate over a function directly using the range keyword without creating an explicit iterator type. This feature simplifies code by letting you define iteration logic inline within a function that returns a channel or uses the new iter.Seq type.
func EvenNumbers(n int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := 0; i < n; i++ {
if i%2 == 0 && !yield(i) {
return
}
}
}
}
for num := range EvenNumbers(10) {
fmt.Println(num)
}