Behavioral

Iterator

Provides sequential access to elements without exposing underlying structure.

Collection traversalCustom iteratorsStreaming data

Understanding Iterator

The Iterator pattern provides a way to access the elements of a collection sequentially without exposing its underlying representation. This separates the traversal logic from the collection itself, allowing different traversal strategies without modifying the collection. In Go, this pattern is built into the language via range for slices and maps, but custom iterators are useful for complex data structures like trees, linked lists, or paginated API results. Go 1.23+ also introduced range-over-func iterators using the iter package.

Key Concepts

  • Iterator interface — provides Next() and HasNext() (or a combined Next() bool pattern) for traversal
  • Collection independence — client code traverses any collection the same way, regardless of internal structure
  • Multiple iterators — a single collection can have multiple active iterators each tracking their own position
  • Lazy evaluation — elements can be computed or fetched on demand rather than all at once

When to Use

✅ Use when
  • • You need to traverse a complex data structure without exposing its internals
  • • You want multiple simultaneous traversals of the same collection
  • • You\'re implementing paginated data fetching from a database or API
  • • The collection\'s internal structure may change but traversal should remain stable
⚠️ Avoid when
  • • A simple slice with range is sufficient in Go
  • • The collection is small and won\'t change — direct indexing is simpler
  • • Go\'s built-in range already handles your traversal needs

Structure

Client
↓ uses
<<Iterator>> Next() HasNext()
↓ traverses
Collection (internal structure)

How It Works

Collection
A
B
C
D
E
Iterator
index: 0
Internal structure hidden
1

Collection

A collection of elements with internal structure.

1 / 4

Basic Implementation

Simple number collection iterator:

main.go
Loading editor...

Real-World Example: User Collection

User collection with filtering iterators:

main.go
Loading editor...