Github: https://github.com/caveofprogramming/rust
Iterators, and the Iterator Interface
The iter()
method of vectors in Rust returns an immutable iterator. This is an instance of the Iter
struct and it implements the Iterator trait. This means we can use it to iterate over the vector.
The Iterator
trait defines various methods, including next()
. We can use this to retrieve items one at a time.
Prints:
In the code above, iter
has to be declared mut
, since it stores its position and we change it by calling next. for
does this behind the scenes.
The Iterator
trait defines various methods, including count()
and sum()
In the above code, we have to declare the type of the things being iterated over somewhere; either after sum()
or else on the variable itself.
We can use iter_mut()
instead of iter()
to get a mutable reference to the items in the vector. Then we can dereference the reference with *
to change the item.
number
here is not an actual number, but a mutable reference to one, so it doesn’t have to be declared with mut
.
Iterator Adapters
Iterator methods that wind the iterator forwards by calling next are called consuming adapters. There are also iterator adapters that don’t consume the iterator.
For example, we can use map with a closure to change the items in the iterator.
Prints:
The Vec<_>
here is needed. The underscore tells Rust to infer the type of the items in the vector.
Another example is the filter method, which creates a filtered copy of the vector.
Prints: