Get the latest tech news
Pure vs. Impure Iterators in Go
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. They promote flexibility and separation of concerns: callers can remain oblivious about how the sequence is produced and can instead focus on what to do with the data; an iterator that abstracts the paginated consumption of GitHub’s API is a good example. In the classic example of a concurrent program ( playground) shown below, the anonymous function is a closure, since it captures (and acts on) variables i and wg, which are both declared in an outer scope:
Or read this on Hacker News