Go 1.23: range over integers and iterator functions
Posted by Kripa Devi · 2024-08-08
Go 1.23 stabilizes range over integers and iterator functions. Clean iteration without allocating intermediate slices. Simple features that compose well. https://github.com/golang/go/releases/tag/go1.23rc1
// Go 1.23 — range over integers + iterators
package main
import "fmt"
func main() {
for i := range 10 {
fmt.Println(i) // 0..9
}
for v := range Fibonacci(10) {
fmt.Println(v)
}
}
func Fibonacci(n int) func(yield func(int) bool) {
return func(yield func(int) bool) {
a, b := 0, 1
for range n {
if !yield(a) { return }
a, b = b, a+b
}
}
}