Iterators Pattern in Rust

 Iterators Pattern in Rust

Iterators Pattern in Rust

Handling a Series of Items with Iterators

The iterator form permits us to perform some task on a sequence of items in turn. An iterator is in authority for the logic of iterating over each item. It is also responsible for determining when the sequence has finished. When we use iterators, we don’t have to re-implement that logic ourselves.

Iterators in Rust are lazy. It means they have no result till we call methods that eat the iterator to use it up. For instance, the code in Listing below creates an iterator over the items in the vector v1 by calling the iter method defined on Vec. This code by itself doesn’t do anything useful.

let v1 = vec![1, 2, 3];

let v1_iter = v1.iter();

We may use it in a variety of ways, when we’ve created an iterator. We used earlier iterators with for loops to execute some code on each item, while we marked over what the call to iter did until now.

The example in Listing below differences the creation of the iterator from the use of the iterator in the for loop. No iteration takes place at that time when the iterator is stored in the v1_iter variable. All element in the iterator is used in one iteration of the loop, which prints out each value, once the for loop is called using the iterator in v1_iter.

let v1 = vec![1, 2, 3];

let v1_iter = v1.iter();

for val in v1_iter {

println!("Got: { }", val);


In languages that don’t have iterators delivered by their normal libraries, we will possible write this same functionality by starting a variable at index 0 and using that variable to index into the vector to become a value. It increments the variable value in a loop till it got the total number of items in the vector.

Iterators handle all that logic for us. By cutting down on repetitive code we could potentially mess up. Iterators give us more flexibility to use the same logic with several diverse kinds of sequences, not just data structures we can index into, like vectors. Let’s inspect how iterators do that.

The Iterator Trait and the next Method

All iterators come in appliance a trait named Iterator that is defined in the standard library. The definition of the trait appearances like this:

pub trait Iterator {

type Item;

fn next(&mut self) -> Option;

// methods with default implementations elided


Some new syntax: type Item and Self::Item are noticeable. These are defining a related type with this trait. This code declares implementing the Iterator trait needs that we also define an Item type. This Item type is definitely used in the return type of the next method. The Item type would be the type returned from the iterator in other words.

The Iterator trait only needs implementers to define one method. The next method returns one item of the iterator at a time wrapped in Some. Once iteration is over, it returns None.

We may call the next method on iterators directly; Listing below proves what values are returned from frequent calls to next on the iterator created from the vector.

Filename: src/

  • test]

fn iterator_demonstration() {

let v1 = vec![1, 2, 3];

let mut v1_iter = v1.iter();

assert_eq!(, Some(&1));

assert_eq!(, Some(&2));

assert_eq!(, Some(&3));

assert_eq!(, None);


We needed to make v1_iter mutable. It is calling the next method on an iterator changes internal state that the iterator uses to keep track of where it is in the sequence. This code consumes in other words, or uses up, the iterator. Altogether call to next eats up an item from the iterator. We didn’t need to make v1_iter mutable. Formerly we used a for loop since the loop took ownership of v1_iter. The loop made it mutable behind the scenes.

The values we get from the calls to next are immutable references to the values in the vector. The iter method forms an iterator above immutable references. We may call into_iter instead of iter if we want to make an iterator that takes ownership of v1 and returns owned values. Likewise, if we want to iterate over mutable references, we may call iter_mut instead of iter.

Powered by Blogger.