Search⌘ K
AI Features

Iterators

Explore how Rust iterators work as lazy sequences that process collections efficiently using methods like next and for loops. Understand implementing custom iterators by creating a Fibonacci sequence example to deepen skills in Rust's 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:

Rust 1.40.0
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().

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

The .next() ...