Skip to main content

What It Is

The Iterator pattern walks through a collection without exposing how it is stored. The caller asks "is there more?" and "give me the next one" — whether the data lives in a slice, a tree or a database stays private.

For plain slices and maps, Go's range already is your iterator. The pattern matters when the storage is hidden or the walk is complicated.


Example: Walking a Playlist

The playlist keeps its songs private. The iterator offers just HasNext() and Next() — the storage behind them could change completely without breaking any caller.

HasNext and Next

The loop never touches the slice inside the playlist. Swap the slice for a linked list or lazy loading, and this loop still compiles and runs.

Prompt
Write a Go program with the Iterator pattern: a Playlist that keeps its songs slice private and hands out an Iterator with HasNext and Next methods. Walk the playlist with the iterator and print each song.
Output: Go program and captured output

When to Use It

Use it when the collection's insides must stay private, when walking is nontrivial (trees, pages from an API), or when you need several independent walks at once.

Skip it for slices and maps in your own code — range is shorter, faster and known to every reader.


Pros and Cons

Pros: storage stays private and changeable; several walks can run independently; complicated traversal is written once.

Cons: more code than range; a live iterator over a changing collection is a classic source of subtle bugs.