Hello! Welcome back to our journey into Rust.
In our last lesson, we dove into closures, the anonymous functions that can capture their environment. You saw how they can be stored in variables and passed as arguments, a feature we noted would be crucial for our next topic. Today, we'll see exactly why, as we explore one of Rust's most powerful and idiomatic features: iterators.
This lesson is all about processing collections efficiently. We will learn how to use iterators to chain operations like map (for transforming data) and filter (for selecting data) in a way that is both highly readable and performant. For someone with experience in C/C++ and Python, you're familiar with for loops. Rust takes this a step further, allowing you to express complex data manipulation without writing explicit loops, often with no performance penalty—a concept known as a zero-cost abstraction. This skill is fundamental to writing effective Rust, from high-level applications all the way to the embedded systems you're aiming to master.
The Iterator Pattern in Rust
At its heart, the iterator pattern is a way to perform a task on a sequence of items. In Rust, an iterator is a struct that implements the Iterator trait, which formalizes the process of moving through a sequence and knowing when it's finished.
All iterators implement the Iterator trait, which has a single required method: next().
pub trait Iterator {
type Item; // An associated type for the items being iterated over
fn next(&mut self) -> Option<Self::Item>;
// ... many other methods with default implementations
}
Each call to next() returns the next item in the sequence wrapped in Some, or None once the sequence is exhausted. This simple contract is the foundation for everything else we'll discuss.
You can get an iterator from most collections in three primary ways, which correspond to Rust's ownership rules:
iter(): Creates an iterator that yields immutable references (&T). The original collection is borrowed and remains untouched.iter_mut(): Creates an iterator that yields mutable references (&mut T). This allows you to modify the items of the collection in place.into_iter(): Creates an iterator that takes ownership of the collection and yields owned values (T). The original collection is moved and cannot be used after this.
Item 9: Consider using iterator transforms instead of explicit loops - Effective Rust
The Effective Rust guide provides an excellent breakdown of how collections produce these different kinds of iterators.
Please read the section titled "Iterator Traits". Focus on how for item in collection, for item in &collection, and for item in &mut collection correspond to calling into_iter(), iter(), and iter_mut() respectively.
Lazy Evaluation: No Work Until Needed
A defining characteristic of Rust's iterators is that they are lazy. This means that just creating an iterator and chaining methods onto it does nothing. No code is executed, and no items are processed until you call a method that consumes the iterator.
Processing a Series of Items with Iterators
The Rust book explains this "lazy" behavior clearly, including the compiler warning you get if you forget to consume an iterator.
Read the section "Methods That Produce Other Iterators". Pay close attention to Listing 13-14 and the resulting compiler warning. This illustrates why methods like map are called "iterator adapters"—they produce a new, un-consumed iterator.
This laziness is a powerful optimization. It allows you to build up complex transformation pipelines without creating intermediate collections at each step, saving both time and memory.
Transforming Sequences with map and filter
Now we get to the core of this lesson: using iterator adaptors to process data. These are methods that take an iterator and produce a new, modified iterator. The two most common adaptors are map and filter.
map: Takes a closure and applies it to each item in the iterator, transforming it into a new item. The closure you provide tomapis what defines the transformation.filter: Takes a closure that returns a boolean. It produces a new iterator that only yields items for which the closure returnstrue.
This is where your knowledge of closures from our last lesson comes directly into play. These methods are powered by the closures you pass to them.
The video "Rust: Iterators" from The Dev Method provides a clear, step-by-step walkthrough of using map and filter.
Watch these two segments: First, watch the explanation of map from the beginning to see how it transforms values and how collect is used to gather the results. Then, watch the following segment on chaining methods, specifically the part about filter, to see how you can combine these adaptors.
Let's look at an example. Suppose we have a vector of numbers and we want to find the squares of all the odd numbers.
let numbers = vec![1, 2, 3, 4, 5, 6];
let squares_of_odds: Vec<i32> = numbers
.iter() // Get an iterator of &i32
.filter(|&&num| num % 2 != 0) // Keep only odd numbers
.map(|&num| num * num) // Square each number
.collect(); // Collect the results into a new Vec
// squares_of_odds is now vec![1, 9, 25]
Notice the &&num in filter. Because iter() produces &i32, the item passed to the closure is &&i32. The && pattern destructures it back to an i32. Similarly, map gets an &i32, which we dereference with *num.
The real power here is in the chaining. The data flows through the pipeline: iter -> filter -> map -> collect. Because of lazy evaluation, Rust is smart about this. It doesn't create a temporary vector after filter. Instead, it processes one item at a time through the entire chain.

Consuming the Iterator to Get a Result
An iterator chain is just a blueprint for computation. To get a final value, you must call a consuming adaptor. These methods consume the iterator, meaning you can't use it again after the call.
The most common consumer is collect(). It can turn an iterator into almost any kind of collection. Because it's so versatile, you often need to provide a type annotation so the compiler knows what collection you want to build.
let numbers = vec![1, 2, 3];
// We must tell `collect` what to create.
let doubled: Vec<i32> = numbers.iter().map(|x| x * 2).collect();
Other useful consumers include:
sum(): Sums the items (if they are numeric).count(): Counts the number of items.last(): Returns the last item as anOption.find(): Takes a closure and returns the first item that satisfies the predicate, wrapped in anOption.
From C-style Loops to Idiomatic Rust
For someone accustomed to C-style loops, this functional style can feel different at first. Let's see how a traditional loop can be refactored into a clean iterator chain.
Item 9: Consider using iterator transforms instead of explicit loops - Effective Rust
This section from Effective Rust provides a perfect, step-by-step transformation of a C-like loop into a modern, idiomatic Rust iterator expression.
Read the section titled "Loop Transformation". Follow each step of the refactoring process closely. This demonstrates how conditions (if), transformations, and accumulation logic inside a loop map directly to filter, map, and consumers like sum.
This transformation isn't just about writing less code. It often expresses the intent of the code more clearly. Instead of focusing on the mechanics of looping (indices, bounds checks, breaking), you describe the data transformation you want to perform.
Conclusion
Today, we've unlocked a core component of idiomatic Rust programming. By combining iterators, closures, and method chaining, you can write expressive, efficient, and safe code for processing collections.
Here are the key takeaways:
- Iterators are lazy: They do no work until a consuming method is called.
- Adaptors vs. Consumers: Iterator adaptors (
map,filter) create new iterators, while consuming adaptors (collect,sum,find) produce a final value. - Method Chaining: You can chain adaptors to build a pipeline that transforms data step-by-step. This is highly readable and efficient.
- Zero-Cost Abstraction: These high-level iterator chains are typically compiled down to machine code that is just as fast as a manual
forloop.
You now have a powerful toolset for handling data. In our next module, we will begin our journey into embedded systems. You'll see how these fundamental Rust concepts, from ownership and borrowing to traits and iterators, provide the foundation for writing safe and robust low-level code.