Skip to content
GDP for Noobs
☰ All patterns
BehavioralIntermediate

Iterator

Loop over any collection with `for range` (Go 1.23+).

01

Explain it like I'm new

Real-life analogy

A Pez dispenser

You don't see the whole stack of candy. You just get the next one each time you ask, and you can stop whenever you like.

😩 The problem

Callers want to loop over your Playlist or an infinite sequence, but exposing the internal slice leaks details, and infinite sequences can't be slices.

💡 The pattern

Return an iter.Seq: a function that calls yield for each value. Callers use plain for range, and break stops the iterator cleanly.

02

Walk through the code

Click a step to highlight its lines. This is a complete program you can copy and run.

main.go
1package main
2
3import (
4 "fmt"
5 "iter"
6)
7
8type Playlist struct{ songs []string }
9
10// All returns an iterator (Go 1.23+). Callers loop with plain `for range`.
11func (p *Playlist) All() iter.Seq2[int, string] {
12 return func(yield func(int, string) bool) {
13 for i, s := range p.songs {
14 if !yield(i+1, s) { // caller said "stop" (e.g. break)
15 return
16 }
17 }
18 }
19}
20
21// Fibonacci is an INFINITE iterator. It only computes what you ask for.
22func Fibonacci() iter.Seq[int] {
23 return func(yield func(int) bool) {
24 a, b := 0, 1
25 for {
26 if !yield(a) {
27 return
28 }
29 a, b = b, a+b
30 }
31 }
32}
33
34// Filter wraps any iterator and keeps only matching values. Generic!
35func Filter[T any](seq iter.Seq[T], keep func(T) bool) iter.Seq[T] {
36 return func(yield func(T) bool) {
37 for v := range seq {
38 if keep(v) && !yield(v) {
39 return
40 }
41 }
42 }
43}
44
45func main() {
46 p := &Playlist{songs: []string{"Gopher Groove", "Channel Surfing", "Panic at the Goroutine"}}
47 for n, song := range p.All() {
48 fmt.Printf("%d. %s\n", n, song)
49 }
50
51 fmt.Print("even fibonacci numbers under 500: ")
52 isEven := func(n int) bool { return n%2 == 0 }
53 for f := range Filter(Fibonacci(), isEven) {
54 if f > 500 {
55 break // stops the infinite iterator cleanly
56 }
57 fmt.Print(f, " ")
58 }
59 fmt.Println()
60}
terminal
Press ▶ Run to execute this program.

This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.

03

When should I use it?

✅ Reach for it when…

  • •Custom collections, lazy or streaming data, paginated APIs, tree traversal.

🚫 Skip it when…

  • •A plain slice works fine and is small. Just return the slice.

🐹 Go tip

The slices and maps packages return iterators: slices.All, maps.Keys, slices.Sorted(maps.Keys(m)).

🌍 You've already seen it in

maps.Keys, slices.Values, strings.SplitSeq (Go 1.24) and bufio.Scanner (an older iterator style).

04

Quick check

One question. No pressure.

Inside an iterator, what does it mean when yield(v) returns false?

Related: Composite, Pipeline