Course contentsShow
← Rust
Lesson 55 of 1,9101. Rust Fundamentals and ToolingFree lesson

Iterators and Adapters

Chain functional operations like map, filter, and fold to transform data lazily.

In this lesson, you will learn how to chain functional operations together to transform data pipelines efficiently using iterators and adapters.

The Power of Pipelines

When you work with collections in Rust, you rarely need to write manual loops. Instead, you can use Iterators to process data one element at a time. The real magic happens when you connect these iterators to Adapters.

An iterator adapter is a method that takes an existing iterator and transforms it into a new, different iterator. Crucially, these adapters are lazy: they do nothing until you explicitly ask for a result (usually by calling a method like collect or fold).

Chaining Operations

Because each adapter returns another iterator, you can chain them together like a assembly line.

  • map: Transforms each item into something else.
  • filter: Keeps only the items that satisfy a condition.
  • fold: "Consumes" the iterator, reducing all values into a single final result.

Consider this example where we take a list of numbers, double only the even ones, and sum the total:

let numbers = vec![1, 2, 3, 4, 5, 6];

let sum_of_doubled_evens: i32 = numbers
    .iter()                  // Create an iterator
    .filter(|&x| x % 2 == 0) // Keep only even numbers
    .map(|&x| x * 2)         // Double them
    .fold(0, |acc, x| acc + x); // Sum them up

// sum_of_doubled_evens is 24 (4 + 8 + 12)

Why does this matter?

Instead of creating temporary vectors or tracking mutable state in a loop, you describe what should happen to the data. Rust’s compiler is excellent at optimizing these chains, often making them just as fast—or faster—than hand-written for loops. By chaining these operations, you keep your code clean, readable, and highly expressive.

Remember, the pipeline doesn't "run" until you reach the final consumer method like fold, collect, or for_each. This "lazy" behavior ensures that you don't perform unnecessary work or allocate memory for intermediate results that aren't actually needed.

Key Takeaway: Iterator adapters allow you to create powerful, lazy data transformation pipelines by chaining map, filter, and fold into a single, declarative expression.