Range Over Iterators in Assembly Language
Here’s the translation of the provided example to Rust:
Starting with version 1.23, Rust 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 vector of all elements in the list. With Rust iterators, we can do it better - as shown below.
All returns an iterator, which in Rust is a trait that can be implemented for custom types.
The iterator function takes another function as a parameter, called yield
by convention (but the name can be arbitrary). It will call yield
for every element we want to iterate over and note yield
’s return value for potential early termination.
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 yield
keeps returning true
.
Since List::all
returns an iterator, we can use it in a regular for
loop.
Packages like std::iter
have a number of useful functions to work with iterators. For example, collect
takes any iterator and collects all its values into a vector.
Once the loop hits break
or an early return, the function passed to the iterator will return false
.
Next example: Errors.