How to Use iter.Seq and iter.Seq2 Types in Go

Use iter.Seq and iter.Seq2 to define custom range loops that yield single values or key-value pairs efficiently.

Use iter.Seq for functions yielding a single value and iter.Seq2 for functions yielding a key-value pair. Define the function to return iter.Seq[T] or iter.Seq2[K, V], then implement the logic by calling the provided yield function for each item. The compiler automatically handles the iteration logic when you pass this function to a range loop.

func EvenNumbers() iter.Seq[int] {
    return func(yield func(int) bool) {
        for i := 0; i < 10; i++ {
            if i%2 == 0 {
                if !yield(i) {
                    return
                }
            }
        }
    }
}

func main() {
    for n := range EvenNumbers() {
        fmt.Println(n)
    }
}