Go 1.27 reference · Slices, Maps, Iterators and JSON
Go iter.Seq (range over functions) Type
Write iterators as functions that yield values, and loop over them with for range like slices and maps.
Go 1.27 Since 1.23
Syntax
type Seq[V any] func(yield func(V) bool) type Seq2[K, V any] func(yield func(K, V) bool)
Parameters
| Parameter | Description |
|---|---|
yield(v) |
Produce a value; returns false when the loop stopped early. |
for v := range seq |
Consume the iterator. |
Examples
package main
import (
"fmt"
"iter"
)
func evens(limit int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := 0; i < limit; i += 2 {
if !yield(i) {
return
}
}
}
}
func main() {
for n := range evens(10) {
fmt.Print(n, " ")
}
fmt.Println()
}
Output
0 2 4 6 8
Run this on your computer — see “Get Started” for setup.
package main
import (
"fmt"
"iter"
)
func numbered(lines []string) iter.Seq2[int, string] {
return func(yield func(int, string) bool) {
for i, l := range lines {
if !yield(i+1, l) {
return
}
}
}
}
func main() {
for i, line := range numbered([]string{"alpha", "beta", "gamma"}) {
if i == 2 {
break // stops the iterator early
}
fmt.Println(i, line)
}
}
Output
1 alpha
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Go 1.23 | Added |
Related
maps.Keys and slices.Sorted· Iterate a map's keys or values; combine with slices.Sorted for a deterministic order, since map iteration is random.- Go For Loops · tutorial