TL;DR ¶ 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 library, and welcomed a couple of iterator factories (i.e. functions or methods that return an iterator) in the slices and maps packages. And Go 1.24 marked the inception in the standard library of even more iterator factories, such as strings.SplitSeq: // SplitSeq returns an iterator over all substrings of s separated by sep. // The iterator yields the same strings that would be returned by Split(s, sep), // but without constructing the slice. // It returns a single-use iterator. func SplitSeq(s, sep string) iter.Seq[string] If you’re not familiar with the syntax and semantics of iterators in Go 1.23+, I recommend you peruse Ian Lance Taylor’s introductory post published on the Go blog. Once you get past the first impression of bewilderment (“Why so many funcs?!”), it’s pretty smooth sailing. Moreover, callers of iterators typically are isolated from whatever complexity is involved in their implementation. As a first example, consider the program below (playground), which features a fact...
First seen: 2025-05-31 15:27
Last seen: 2025-05-31 18:29