Iterators

Get introduced to iterators, which are another major cornerstone of functional programming.

We'll cover the following...

Iterators

An iterator is a trait that allows us to perform the same task over a collection of elements in turn. Iterators are lazy.

The canonical definition of an iterator takes the form of the .iter() method on iterables. However, the simplest use of an iterator is through the method .next().

There are many more methods and higher-order functions for the use of iterators. There are also some well-known iterables we should learn.

Let’s look at an example:

Press + to interact
let v = vec![1, 2, 3, 4, 5];
let v_iter = v.iter();
println!("{:?}", v_iter);

If we run the code above, we see that v_iter is an iterator Iter([1, 2, 3, 4, 5]).

However, because iterators are lazy, nothing gets done, because the iterator is not used.

Let’s try to use the iterator in its simplest form: next().

Press + to interact
let v = vec![1, 2, 3, 4, 5];
let mut v_iter = v.iter();
println!("{:?}", v_iter.next());

The .next() ...