TL;DR

A Go iterator is a function of type iter.Seq[V]: it takes a yield func(V) bool, calls yield(v) for each value, and returns the moment yield returns false. The contract hasn’t changed since Go 1.23 shipped the iter package and range-over-func in August 2024; the Go 1.27 release notes list no changes to it. Skip the return check and the runtime panics as soon as a caller breaks out early.

Walking two sequences side by side, as in a zip, needs iter.Pull, which ran about 30x slower per element than a plain push loop in the build-server benchmark below. This post covers iter.Seq, iter.Seq2, early termination, iter.Pull, a Zip you can paste into your codebase (the stdlib still has none), and the iterator functions in maps and slices.

Why iterators finally landed

For a decade Go had exactly one way to iterate: range over a built-in type (slice, map, string, channel, int). If you wanted to walk a custom tree, a paginated API, or an unbounded sequence, you either returned a slice (eager, allocating) or wrote a channel-based generator (leaky, slow). Libraries tried callback methods and visitor interfaces, and neither composed well across packages.

Go 1.22 (February 2024) shipped range-over-func as an experiment behind GOEXPERIMENT=rangefunc. Go 1.23 (August 2024) made it stable, added the iter package, and added iterator-returning functions to maps and slices. Go 1.24 through 1.26 kept refining the corners, with 1.26 adding reflect iterators (Type.Fields(), Type.Methods(), and more). By 2026 the feature is stable and unremarkable, which is what you want from a loop construct. Go’s generics story kept moving in parallel: Go 1.27, released in August 2026, added generic methods, and its go fix gained a slicesbackward modernizer that rewrites hand-written reverse index loops into range slices.Backward(s). The Go blog’s design post walks through the design rationale if you want the historical read.

The two types you need to know

The entire iter package fits in a dozen lines of signatures:

package iter

type Seq[V any]     func(yield func(V) bool)
type Seq2[K, V any] func(yield func(K, V) bool)

func Pull[V any](seq Seq[V])   (next func() (V, bool), stop func())
func Pull2[K, V any](seq Seq2[K, V]) (next func() (K, V, bool), stop func())

Seq[V] is the default. It yields one value per step, like ranging over []int or <-chan string. Seq2[K, V] yields two, like ranging over a map or an indexed slice. Go chose two separate types (instead of one generic tuple) because otherwise for i, v := range seq would have needed a tuple type the language doesn’t have, and two named types keep for range readable.

Your first iterator

Here’s a counter that yields integers from start to end-1:

func Count(start, end int) iter.Seq[int] {
    return func(yield func(int) bool) {
        for i := start; i < end; i++ {
            if !yield(i) {
                return
            }
        }
    }
}

func main() {
    for n := range Count(0, 5) {
        fmt.Println(n)
    }
}

Three things to notice. First, Count returns a closure that captures start and end; that closure is your iterator. Second, the body is a plain loop you already know how to write. Third, the if !yield(i) { return } is the whole contract in a single line: each call to yield checks whether the consumer still wants more.

Skip that check and you have a bug. The consumer might break out of the for range, or call your iterator inside iter.Pull and abandon it early, or panic partway through. If you keep calling yield after it’s returned false, Go will panic with runtime error: range function continued iteration after function for loop body returned false. The runtime catches this explicitly, so a test that breaks early surfaces the bug instead of a silent resource leak reaching production.

Seq2: when you need two values

A tree traversal that yields (depth, value) pairs:

type Node[T any] struct {
    Value       T
    Left, Right *Node[T]
}

func (n *Node[T]) Walk() iter.Seq2[int, T] {
    return func(yield func(int, T) bool) {
        var visit func(*Node[T], int) bool
        visit = func(n *Node[T], depth int) bool {
            if n == nil {
                return true
            }
            if !visit(n.Left, depth+1) {
                return false
            }
            if !yield(depth, n.Value) {
                return false
            }
            return visit(n.Right, depth+1)
        }
        visit(n, 0)
    }
}

Usage:

for depth, v := range root.Walk() {
    fmt.Printf("%*s%v\n", depth*2, "", v)
}

Recursion + iterators is where the return bool pattern pays off. Each recursive call forwards whatever yield returned, so a break three levels deep unwinds all the way up without any goroutines, channels, or shared state. The Go blog’s binary tree example uses the same trick.

Early termination is the real point

Slices are fine when you know the sequence is small. Iterators earn their keep when it’s big or unbounded.

// Return the first matching line without reading the whole file.
func FirstMatch(lines iter.Seq[string], pattern string) (string, bool) {
    for line := range lines {
        if strings.Contains(line, pattern) {
            return line, true
        }
    }
    return "", false
}

The return inside the for range triggers the iterator’s internal yield to return false, which is how the iterator knows to clean up and exit. If lines is wrapping a file handle, an HTTP paginator, or a database cursor, the producer can close its resources on that path, assuming it was written with the contract in mind.

1.23
Go version shipped iter stable
2
Types in the package: Seq, Seq2
~30x
iter.Pull cost per element vs push (Go 1.24 run below)

Composing iterators: filter and map

You won’t find Filter or Map in the stdlib either; the adapter package that would have held them was retracted (more on that in the Zip section below). Each one is a few lines to write yourself:

func Filter[V any](seq iter.Seq[V], pred func(V) bool) iter.Seq[V] {
    return func(yield func(V) bool) {
        for v := range seq {
            if pred(v) && !yield(v) {
                return
            }
        }
    }
}

func Map[A, B any](seq iter.Seq[A], fn func(A) B) iter.Seq[B] {
    return func(yield func(B) bool) {
        for a := range seq {
            if !yield(fn(a)) {
                return
            }
        }
    }
}

Now you can do Map(Filter(Count(0, 1000), even), square) and get a lazy pipeline that only does work as the consumer pulls. Each stage re-checks yield’s return value, so a break in the outer loop propagates through the whole chain. There are no goroutines involved and no per-element allocation; the only cost is a handful of closures per pipeline.

Push vs pull, and when you need iter.Pull

Range-over-func gives you a push iterator: the producer drives the loop and pushes values into yield. Most Go code wants push, because it matches how for range reads.

But sometimes you need to pull. The canonical example is comparing two sequences element-by-element:

func Equal[V comparable](a, b iter.Seq[V]) bool {
    nextA, stopA := iter.Pull(a)
    defer stopA()
    nextB, stopB := iter.Pull(b)
    defer stopB()

    for {
        va, okA := nextA()
        vb, okB := nextB()
        if okA != okB {
            return false
        }
        if !okA {
            return true
        }
        if va != vb {
            return false
        }
    }
}

You cannot do this with two nested for range loops, because they’d each want to drive their own control flow. iter.Pull flips the push iterator inside out and hands you a next() function that blocks until the underlying iterator yields a value. The defer stop() is not optional: if you return from Equal without stopping both pull iterators, the coroutines that back them will leak.

Pull runs your push iterator inside a runtime coroutine (not a goroutine: the implementation uses runtime.newcoro/coroswitch rather than go plus channels, which is a lot cheaper) and blocks each yield call until the consumer asks for the next value. Even a cheap coroutine switch per element adds up. A quick benchmark on the blog’s build server (Go 1.24.0, 2-core Xeon) summed the integers 0–999 through a push iterator and through iter.Pull wrapping the same iterator:

BenchmarkPush-2   330284      3495 ns/op    56 B/op    4 allocs/op
BenchmarkPull-2    10296    111947 ns/op   368 B/op   13 allocs/op

That’s about 3.5 ns per element with push and about 112 ns with Pull, roughly 30x slower on a tight loop (five runs each, all within a few percent). The loop body here does almost nothing, so real code narrows the gap. Still, Pull belongs on lockstep comparisons and other genuinely pull-shaped problems, and a plain for range belongs everywhere else.

Zipping two iterators

The most common pull-shaped problem is a zip: walk two sequences together and hand back one element from each per step. Go’s standard library doesn’t ship a Zip. Russ Cox’s 2023 x/exp/xiter proposal included one alongside Filter, Map, Concat and friends, but the proposal was retracted and closed in May 2025, and Go 1.27 still ships no iterator adapters. Writing your own takes about ten lines:

// Zip yields pairs (a[i], b[i]) and stops when either sequence runs out.
func Zip[A, B any](a iter.Seq[A], b iter.Seq[B]) iter.Seq2[A, B] {
    return func(yield func(A, B) bool) {
        nextB, stopB := iter.Pull(b)
        defer stopB()
        for va := range a {
            vb, ok := nextB()
            if !ok || !yield(va, vb) {
                return
            }
        }
    }
}

Only one side gets pulled. a stays a normal push iterator that drives the outer for range, and b is converted with iter.Pull so the loop can ask it for exactly one value per step. That means one coroutine instead of two, and defer stopB() cleans up b however the loop exits: a running dry, b running dry, or the consumer breaking out. Returning iter.Seq2[A, B] instead of a pair struct means callers get the two-variable range form for free:

names := slices.Values([]string{"ada", "grace", "ken"})
scores := slices.Values([]int{91, 88})

for name, score := range Zip(names, scores) {
    fmt.Println(name, score)
}

That loop runs twice: “ken” has no partner score, so nextB reports ok == false on the third step and Zip returns. If you need the longest-sequence behaviour instead, follow the retracted proposal’s design: yield a struct carrying both values plus an Ok1/Ok2 flag for each side, and keep going until both sequences are exhausted. The shortest-wins version above covers the usual cases (pairing keys with values, comparing two streams, merging a header row with data rows), and it’s the semantics Python’s zip() uses by default. When both inputs are already slices, skip iterators entirely and index them in a plain for i := range min(len(a), len(b)) loop, which is cheaper than any coroutine.

What the stdlib does now

Go 1.23 added iterator methods across the stdlib, which is the cleanest way to learn the idiom by example:

FunctionReturnsNotes
slices.All(s)iter.Seq2[int, V]index + value, replaces for i, v := range s when you need composition
slices.Values(s)iter.Seq[V]values only
slices.Backward(s)iter.Seq2[int, V]index + value from the end; Go 1.27’s go fix rewrites manual reverse loops to it
slices.Sorted(seq)[]Vcollects an iterator into a sorted slice
maps.All(m)iter.Seq2[K, V]unordered key-value pairs
maps.Keys(m)iter.Seq[K]keys only
maps.Values(m)iter.Seq[V]values only

The pattern slices.Sorted(maps.Keys(m)) (get all keys, sort them) is the compact replacement for the old five-line “copy keys into a slice, sort, return” dance. Read the slices and maps package docs for the full list. Several functions that build a []T now have a sibling that returns an iterator instead.

Three common mistakes

Forgetting the !yield check. Classic bug: you write yield(v) inside a loop, forget to test the return, and the consumer can’t break out. Go will panic loudly on the second call after yield returned false, but only if a consumer actually stops early. In tests that consume the full sequence the bug is invisible. Write the check every time, even when “the sequence is always finite.”

Holding resources across a user-controlled yield. If your iterator opens a file, acquires a lock, or starts a transaction, the consumer can break at any point. Use defer inside the iterator body for cleanup. It runs whether the loop completed, broke early, or panicked:

func Lines(path string) iter.Seq[string] {
    return func(yield func(string) bool) {
        f, err := os.Open(path)
        if err != nil {
            return
        }
        defer f.Close()
        s := bufio.NewScanner(f)
        for s.Scan() {
            if !yield(s.Text()) {
                return
            }
        }
    }
}

A database cursor follows the same shape. Query code for database/sql, whether hand-written or generated by sqlc (compared with GORM and Ent in this database library breakdown), ends up looping over *sql.Rows. Put defer rows.Close() at the top of the iterator and if !yield(row) { return } inside the rows.Next() loop, and a caller that stops after the first match releases the connection right away.

Pull without defer stop(). Every iter.Pull call spins up a runtime coroutine. Forget the stop() on an early exit and the iterator function never finishes: its coroutine stays parked, and so does whatever it holds, such as an open file or a lock, because its deferred cleanup never runs. Make next, stop := iter.Pull(seq) and defer stop() a fixed two-line pair.

Error handling

The iter.Seq signature has no error channel, which bothers people at first. Three patterns cover the real cases:

  1. Seq2 with an error second value: iter.Seq2[T, error]. The consumer writes for v, err := range things { if err != nil { ... } }. Good for streams where most items succeed and errors are occasional.
  2. A result type: define type Result[T any] struct { V T; Err error } and yield Result[T]. More ceremony, but composes cleanly with Filter/Map.
  3. An error getter on the iterator: run the loop, then call it.Err() afterwards, the same pattern bufio.Scanner uses. Works when errors are terminal rather than per-item.

Option 3 is the precedent in the stdlib (bufio.Scanner), and option 1 is the shape many community database and HTTP-pagination wrappers have picked since 1.23. Pick by whether errors are per-item (option 1 or 2) or terminal (option 3). A token stream is a good test case for option 1: the jsontext.Decoder in Go’s JSON v2 returns (Token, error) from every ReadToken call, so wrapping it as an iter.Seq2[jsontext.Token, error] maps one call to one step.

FAQ

How do you write a custom iterator in Go?

Return a function of type iter.Seq[V], which is func(yield func(V) bool). The function should call yield(v) for each value and return the moment yield returns false. Wrap that function in a closure or a method so it captures whatever state it needs to walk the sequence.

What is the difference between Seq and Seq2?

Seq[V] yields one value per step; Seq2[K, V] yields two. Use Seq2 when you need pairs like (index, value) or (key, value), because for k, v := range seq2 requires exactly this type.

What is range-over-func in Go?

It’s the feature added in Go 1.22 (experimental) and Go 1.23 (stable) that lets for range work on a function of type iter.Seq or iter.Seq2. The compiler rewrites the loop body into the yield function, so there’s no hidden goroutine for push iterators.

How do you convert a push iterator to a pull iterator?

Call iter.Pull(seq). It returns (next, stop), where next() pulls one value at a time and stop() cleans up. Always defer stop() because Pull starts a runtime coroutine you have to unwind.

How do you zip two iterators in Go?

Convert one of them with iter.Pull and range over the other: for each value from the first sequence, call next() on the second, and stop when either side is exhausted. The ten-line Zip in the section above does exactly that and returns an iter.Seq2, so callers write for a, b := range Zip(x, y). There’s no Zip in the standard library; the x/exp/xiter proposal that would have added one was retracted in 2025.

Do iterators allocate?

A push iterator costs a few closures per call and nothing per element. In the build-server benchmark above, the push version summed 1,000 integers with 4 allocations totalling 56 bytes, at about 3.5 ns per element. When the compiler can inline the iterator and the loop body, a hot for v := range seq comes close to a hand-written index loop. iter.Pull costs more (13 allocations and roughly 30x the time per element in the same run), which is why you’d only reach for it when you genuinely need pull semantics.

For the rest of what changed in Go since 1.22, see the modern Go guide.

Sources

Bottom line

Iterators let a caller walk a custom collection lazily with the same for range syntax Go always had, and they add one idiom rather than a functional-programming layer. Two years in, my rule is to reach for iter.Seq wherever I’d have returned a slice, and to stop writing channel-based generators. Learn the yield contract, defer your cleanups, and keep iter.Pull for the cases that really need two sequences in lockstep, like the Zip above. If you’re weighing Go against Rust for a backend project, the Rust vs Go comparison covers performance and hiring.