Iterators and Enumerators in Rust

Introduction to Iterators and Enumerators in Rust

Hello! In this lesson, we are going to explore a fundamental aspect of Rust programming: Iterators and Enumerators. Iterators are an essential tool in Rust, allowing you to traverse sequences of data efficiently. They offer a convenient and idiomatic way to manipulate collections.

By the end of this lesson, you'll be proficient in iterating over arrays, vectors, strings, and hash maps. We'll break down each topic into understandable and practical steps, so you can follow along and implement them in your own code seamlessly.

Let's dive in!

Introducing `iter`

Before we delve into specific examples of iterating over various types of collections, let's first introduce two fundamental methods in Rust: iter and enumerate.

The iter method is commonly used to create an iterator from a collection. This method is available for arrays, vectors, and hash maps, allowing you to traverse through them element by element.

fn main() {
    let numbers = [1, 2, 3, 4, 5];

    // Using `iter` to get an iterator over the array
    for value in numbers.iter() {
        println!("Value: {}", value);
    }
}
/* Output:
    Value: 1
    Value: 2
    Value: 3
    Value: 4
    Value: 5
*/

The code for value in numbers.iter() uses the iter method to create an iterator over the array numbers. The for loop then iterates over each element. Within the loop, each element (referred to as value) is printed. For each iteration, the placeholder {} is replaced with the current value.

Pairing `iter` and `enumerate`

The enumerate method builds upon the base iterator to provide a sequence of pairs, where each pair consists of an index and a reference to the value at that index. This is particularly useful when you need to keep track of the position of each item within the collection. Let's take a look.

fn main() {
    // Defining an array
    let numbers = [1, 2, 3, 4, 5];

    // Using `iter().enumerate()` on the array
    for (index, value) in numbers.iter().enumerate() {
        println!("Index: {}, Value: {}", index, value);
    }
}
/* Output
    Index: 0, Value: 1
    Index: 1, Value: 2
    Index: 2, Value: 3
    Index: 3, Value: 4
    Index: 4, Value: 5
*/

for (index, value) in numbers.iter().enumerate() uses both the iter and enumerate methods. iter creates an iterator over the array, and enumerate transforms this iterator into one that yields pairs of (index, value), where index is the position of the element in the array and value is the reference to the element.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal