Starting with version 1.23, the language has added support for iterators, which lets us range over pretty much anything!
Let’s look at the List type from the previous example again. In that example, we had an AllElements method that returned a slice of all elements in the list. With iterators, we can do it better - as shown below.
All returns an iterator, which in this language is implemented using the yield keyword within a generator function.
The iterator function takes another function (the generator) as parameter, which will yield every element we want to iterate over, and allowing for a potential early termination when required.
Iteration doesn’t require an underlying data structure, and doesn’t even have to be finite! Here’s a function returning an iterator over Fibonacci numbers: it keeps running as long as the generator keeps yielding values.
Now that we know how to work with iterators and generators in this language, let’s explore more of its advanced features.