Pure vs. Impure Iterators in Go
Published on: 2025-06-09 09:57:38
Go has now standardised iterators.
Iterators are powerful.
Being functions under the hood, iterators can be closures.
The classification of iterators suggested by the documentation is ambiguous.
Dividing iterators into two categories, “pure” and “impure”, seems to me preferrable.
Whether iterators should be designed as “pure” whenever possible is unclear.
The advent of iterators in Go ¶
The iterator pattern was popularised by the classic “Gang of Four” book as
[providing] a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Until recently, the data structures over which you could iterate via a for - range loop were limited to arrays (either directly or through a pointer), slices, strings, maps, channels, and integers. However, in the wake of Go 1.18’s support for parametric polymorphism (a.k.a. “generics”), Go 1.23 standardised the way of defining custom iterators, saw the addition of the iter package in the standard
... Read full article.