Processing a Series of Items with Iterators in Rust

Reading Time: 3 minutes

Iterators are objects that produce sequences of values, so they can be iterated or looped over. Or, in other words, every time you ended up using a for loop in your program, you were most likely interacting with some kind of iterator.

Hello, folks! your wait is over, we have come up with a new blog. In this blog, we will discuss Iterators to process of series of items and its use cases in Rust programming language with the help of a sample example. I hope you will enjoy the blog.

Iterators:

An Iterators is responsible for the logic of iterating over each item and determining when the sequence has finished. When you use iterators, you don’t have to re-implement that logic yourself.

In Rust, iterators are lazy, meaning they have no effect until you call methods that consume the iterator to use it up.

Lets creates an iterator over the items in the vector vector by calling the iter method defined on Vec<T>.

fn main() {
    let vector = vec![1, 2, 3];

    let vector_iter = vector.iter();
}

Once we’ve created an iterator, we can use it in a variety of ways. like in for loop to execute some code on each item.

For example:

fn main() {
    let vector = vec![1, 2, 3];

    let vector_iter = vector.iter();

    for val in vector_iter {
        println!("value form the vector: {}", val);
    }
}

The Next method in the iterator trait:

The Iterator trait comes with a next() method that returns Option<Self::Item>. The exact type of Self::Item depends on the values the iterator produces. What’s more interesting however, is that it’s wrapped in an Optionnext() returns the next value of the iterator and because it could potentially run out of values, returning an Option enables the API to return None in such cases. This also means that iterators are stateful because they keep track of where they are in the iteration process. There are some more methods attached to the trait but we can ignore those for now.

Example:

fn main() {
    let vector = vec![5, 6, 7];

    let mut vector_iter = vector.iter();
    println!("{:?}",vector_iter.next());
    println!("{:?}",vector_iter.next());
    println!("{:?}",vector_iter.next());
    println!("{:?}",vector_iter.next());
}

Output:

This image has an empty alt attribute; its file name is screenshot-from-2020-11-06-15-31-09.png

The next method for using counter iterator:

We can use the iterator functionality of our Counter struct by calling the next method on it directly. This test creates a new Counter instance in the counter variable and then calls next repeatedly,

For example:

struct Counter {
    count: u32,
}

impl Counter {
    fn new() -> Counter {
        Counter { count: 0 }
    }
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.count < 5 {
            self.count += 1;
            Some(self.count)
        } else {
            None
        }
    }
}

fn main() {
    let mut counter = Counter::new();
    
    println!("{:?}", counter.next());
    println!("{:?}", counter.next());
    println!("{:?}", counter.next());
    println!("{:?}", counter.next());
    println!("{:?}", counter.next());
    println!("{:?}", counter.next());
    println!("{:?}", counter.next());
}

Output:

This image has an empty alt attribute; its file name is screenshot-from-2020-11-06-15-53-36.png

In this example, we have created a Counter structure and implemented the iterator for that counter structure in which we have created the next function which can increase the counter for 5 times which we will help our programs to run our code for the limited iterations.

Note: I hope our blogs help you to enhance your learning. I’ll post more blogs on Rust. Stay Tuned.

If you want to read more content like this?  Subscribe Rust Times Newsletter and receive insights and latest updates, bi-weekly, straight into your inbox. Subscribe Rust Times Newsletter: https://bit.ly/2Vdlld7 .

Happy learning!!!

This image has an empty alt attribute; its file name is screenshot-from-2020-06-08-11-00-35.png
This image has an empty alt attribute; its file name is footer-2.jpg

Written by 

Pankaj Chaudhary is a Software Consultant at Knoldus LLP. He has 1.5+ years of experience with good knowledge of Rust, Python, Java, and C. Now he is working as Rust developer and also works on machine learning and data analysis because he loves to play with data and extract some useful information from it. His hobbies are bike riding and explore new places.

Leave a Reply