HowtoGo
Home / Standard Library / The iter Package
Standard Library

The iter Package

iter holds two function types and two functions. Everything in Go that hands back a sequence, maps.Keys and slices.All included, is shaped by what is on this page.

Examples

An iterator is a function that takes yield and calls it once per element.

// Words returns an iterator over the whitespace-separated words in s.
func Words(s string) iter.Seq[string] {
    return func(yield func(string) bool) {
        for _, w := range strings.Fields(s) {
            if !yield(w) {
                return
            }
        }
    }
}

func main() {
    for w := range Words("the quick brown fox") {
        if w == "brown" {
            break
        }
        fmt.Println(w)
    }
}
Output
the
quick

Types

TypeDescription
type Seq[V any] func(yield func(V) bool)
A sequence of single values. A range loop over one of these calls it.
type Seq2[K, V any] func(yield func(K, V) bool)
A sequence of pairs. Key and value, or index and value.

Functions

FunctionDescription
Pull[V any](seq Seq[V]) (next func() (V, bool), stop func())
Turns a sequence into a next() you call yourself.
Pull2[K, V any](seq Seq2[K, V]) (next func() (K, V, bool), stop func())
next, stop := iter.Pull2(seq)
The same, for a sequence of pairs.

The yield contract

Check what yield returns. A false means the loop body ran a break, a return, or a goto, and the iterator has to return there and then.

One more call panics. Once yield has returned false, calling it again takes the program down. This is why the check is written as an early return rather than a flag you test later.

Say so when a sequence runs once. An iterator over a network stream or a scanner cannot be restarted, and the caller has no way to tell from the type. Document it on the function that returns it.