Pure vs. Impure Iterators in Go
a year ago
- #Programming
- #Iterators
- #Go
- Go has standardized iterators with the introduction of generics in Go 1.18, enhancing flexibility and performance.
- Iterators in Go can be classified into 'pure' (stateless, no observable side effects) and 'impure' (stateful, with side effects).
- The official documentation introduces 'single-use iterators' as a subcategory of impure iterators, but this classification is seen as ambiguous and imprecise.
- Pure iterators are easier to reason about and can reduce heap allocations, making them preferable from a performance standpoint.
- However, consistency with related iterators (like those in the bytes package) may necessitate the use of impure iterators in some cases.
- The Go community is still establishing conventions around iterators, with ongoing discussions about terminology and best practices.