Rust Iterators: Fire Your for Loops (They'll Be Fine, They Have Savings)

Your for loop has been doing three jobs at once and it's tired. Rust iterators split the work into map, filter and sum, cost nothing extra at run time, and are lazier than a cat in a sunbeam. A ten-minute lab.

Ada Brackett

4 min read

Look at your for loop. Really look at it. It's keeping a running total, checking an if, pushing into a vector and tracking an index, all at once. It's the guy at the office who runs payroll, fixes the printer and organises the birthday cake. It hasn't taken a holiday since 2011.

Today we let it go. Gently. With a nice card. Rust iterators split all that work into small, named steps that each do one thing.

This is like the time I hired one guy to move my entire flat. [He's carrying the sofa, the fridge and a goldfish bowl, all at once, down a spiral staircase. The goldfish looks extremely worried.] Iterators are hiring three movers. The goldfish lives.

The old way

Bash
cargo new scores
cd scores

Here's a loop doing three jobs, in src/main.rs:

Rust
fn main() {
    let scores = vec![72, 95, 41, 88, 60];

    let mut passed = Vec::new();
    let mut total = 0;
    for s in &scores {
        total += s;
        if *s >= 60 {
            passed.push(*s);
        }
    }
    println!("passed: {passed:?}, total: {total}");
}

It works. It's also four lines of bookkeeping you have to read carefully to find out what it means.

The iterator way

Rust
fn main() {
    let scores = vec![72, 95, 41, 88, 60];

    let passed: Vec<i32> = scores.iter().copied().filter(|&s| s >= 60).collect();
    let total: i32 = scores.iter().sum();
    let best = scores.iter().max();

    println!("passed: {passed:?}, total: {total}, best: {best:?}");
}
passed: [72, 95, 88, 60], total: 356, best: Some(95)

Each line says what it does. Here are the pieces:

  • .iter() walks the vector, lending you each item as &i32.
  • .copied() turns &i32 into a plain i32. Numbers are cheap to copy, so there's no reason to keep borrowing them.
  • .filter(|&s| s >= 60) keeps only the items that pass the test. The |&s| ... part is a closure, a tiny unnamed function.
  • .collect() gathers the results into whatever type you asked for, here Vec<i32>.
  • .sum() and .max() do exactly what they say. max returns an Option, because an empty list has no best score. Rust is honest about this. Your loop with let mut best = 0 was quietly lying.

Iterators are lazy (respectfully)

Here's the strange part. This does nothing:

Rust
scores.iter().map(|s| {
    println!("looking at {s}");
    s * 2
});

Nothing prints. The compiler even warns you that the Map is unused and must be used. An iterator is a plan, not an action. Nothing happens until something at the end asks for the values: collect, sum, for, count. It's lazier than a cat in a sunbeam, and just like the cat, it only moves when there's food.

That laziness is a superpower. This stops after finding three items, even if the list has a million:

Rust
let first_three: Vec<i32> = scores.iter().copied().filter(|&s| s >= 60).take(3).collect();

Two more you'll use every day

enumerate gives you the index without a counter variable:

Rust
for (i, s) in scores.iter().enumerate() {
    println!("student {}: {s}", i + 1);
}

zip walks two lists side by side:

Rust
let names = ["Ana", "Ben", "Cy", "Dee", "Eve"];
for (name, s) in names.iter().zip(&scores) {
    println!("{name}: {s}");
}

If one list is shorter, zip stops at the end of the shorter one. No off-by-one panic. No index arithmetic. No goldfish casualties.

"But is it slow?"

No. This is the best part. Rust iterators are a zero-cost abstraction: the compiler turns that chain of iter().filter().sum() into machine code as tight as the loop you'd write by hand, often tighter. You get the readable version and pay nothing at run time for it. That's like ordering the salad and getting the burger's taste.

When to keep the for loop

for loops aren't fired, just promoted to a role that suits them. Keep using for when you're doing something with side effects on each item, such as printing, writing to a file or sending a request. Use an iterator chain when you're computing a value: filtering, transforming, totalling. A good rule of thumb: if your loop body starts with let mut, there's probably an iterator for that.

Homework

  • Work out the average score: total as f64 / scores.len() as f64. Bonus points if you handle an empty list without dividing by zero.
  • Use .map(|s| if s >= 60 { "pass" } else { "fail" }) with zip to print each name with pass or fail.
  • Try .fold(), the iterator that can do anything. Use your powers wisely.

Next time we tackle the one topic that makes grown developers whisper: lifetimes. Bring snacks.