Go 1.23 Iterators: Use Range Syntax When It Makes the API More Honest
Go 1.23 added range-over-function iterators and the standard iter package. A function can now yield a sequence that callers consume with familiar for-range syntax. This makes it easier to expose a lazy view over a collection, a tree, or a custom traversal without first allocating a complete slice.
The feature is most useful when the producer controls traversal and the caller should decide when to stop. A well-designed iterator can support early exit naturally: the loop ends, and the yield function tells the producer not to continue. That is a better abstraction than returning a large intermediate slice when callers often use only the first few results.
There is still a cost to introducing the abstraction. A simple slice is often clearer for small, already-materialized results. Iterators can make control flow less obvious if the producer performs I/O, mutates shared state, or hides expensive work behind each yielded value. Document whether iteration is repeatable, whether it can fail, and which resources it holds open.
Keep cancellation and error propagation explicit. The standard iterator function shapes do not magically add a context or an error channel. If iteration can block on a database or network call, design an API that makes cancellation and failure visible rather than disguising them inside a range loop.
Fit score: 7.5/10 for reusable collection APIs and tree walks; lower for one-off loops where a slice is perfectly readable. Go’s 1.23 release notes and range-over-function article describe the standard iterator forms and helpers.