☰ All patterns
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.
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?