Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 132 ยท Collections and Iterators

Iterators

Learn Rust iterators from scratch - the Iterator trait, next(), iter, iter_mut and into_iter, lazy adapters like map and filter, consumers like sum and collect, and common pitfalls.

An iterator is something that hands you values one at a time. You have already used one without naming it: every for loop over a Vec or a range runs an iterator behind the scenes. Rust makes iterators a central tool. Instead of writing index loops and mutable counters, you describe a pipeline: "take these numbers, keep the even ones, square them, add them up". The compiler turns that pipeline into the same machine code you would have written by hand.

This lesson explains what an iterator really is (a small trait with one required method), the three ways to iterate over a collection, how adapters like map and filter stay lazy until something consumes them, and the consumers that finally produce a result. The next lesson goes deeper into collect and recipes, and Writing Your Own Iterators shows how to build your own.

The Iterator trait

Everything starts with a trait from the standard library. Slightly simplified, it looks like this:

Rust
trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
    // ...dozens of provided methods like map, filter, sum...
}

An iterator has an associated type Item (what it produces) and one required method, next. Each call to next returns Some(value) while there are values left and None once it is finished. That is the whole protocol. All the other methods (map, filter, sum, collect and the rest) are provided by the trait and are built on top of next.

Because next takes &mut self, an iterator is a little state machine: it remembers where it is. You can drive it by hand:

Rust Calling next by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first three calls return Some(&10), Some(&20) and Some(&30). After the data runs out, every further call returns None. Notice the &: iter() yields references to the elements, not the elements themselves. We will come back to that in a moment.

A for loop is just sugar over this protocol. This loop:

Rust
for x in collection {
    // body
}

is roughly: call into_iter() on the collection, then repeatedly call next() and run the body on every Some(x), stopping at None. That is why anything that implements IntoIterator works in a for loop.

iter, iter_mut and into_iter

A collection gives you three different iterators, and the difference is ownership:

Method Item type for Vec<T> Effect
iter() &T Borrows each element read-only. The vector stays usable.
iter_mut() &mut T Borrows each element mutably so you can change it in place.
into_iter() T Consumes the vector and moves each element out.
Rust Three kinds of iteration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The for name in &names form is shorthand for names.iter(), and for name in &mut names means names.iter_mut(). Plain for name in names calls into_iter() on the vector itself and consumes it.

Use iter() by default. Reach for iter_mut() when you need to modify elements in place, and into_iter() when you want to take ownership, for example to move strings into another collection without cloning them.

For Copy types like i32, references are still what iter() produces, so you will often see *x or .copied() to get the plain value. The copied() and cloned() adapters are covered below.

Adapters are lazy

An adapter takes an iterator and returns a new iterator that does something extra: map, filter, enumerate, zip, take, skip, chain, rev and many more. The key fact is that adapters are lazy. Building a pipeline does no work at all. Nothing is computed until a consumer pulls values through the chain.

Rust Proof that adapters are lazy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The "mapping" lines only appear after collect() runs. The compiler also warns if you build an adapter and never use it, because that code does nothing: warning: unused `Map` that must be used with the note "iterators are lazy and do nothing unless consumed".

Laziness has real benefits. A pipeline over a million items that ends with .take(3) only computes three items. It also means the whole chain is processed one item at a time, with no intermediate vectors: each value flows through filter, then map, then the consumer before the next one starts.

The adapters you will use most

Rust A tour of common adapters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A few notes on what you just saw:

  • filter passes its closure a reference to the item, so with iter() over &str the closure receives a reference to a reference. Auto-dereferencing in method calls such as w.len() hides this, but a comparison like *w == "date" needs explicit dereferences. When types get confusing, .copied() or .cloned() before filter strips a level of reference.
  • rev() needs an iterator that can run from both ends (a DoubleEndedIterator). Ranges, slices and vectors can; many others cannot.
  • zip stops as soon as either side ends, so mismatched lengths never panic.
  • copied() turns an iterator of &T into one of T for Copy types; cloned() does the same by cloning, for example Vec<String> items.

peekable and windows

peekable() wraps an iterator so you can look at the next item without consuming it, which is perfect for parsers. Slices (not iterators) also offer windows(n) (overlapping groups) and chunks(n) (non-overlapping groups).

Rust peekable, windows and chunks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Consumers

A consumer (also called a terminal operation) drives the iterator to completion, or until it has an answer, and returns a value. These are the ones to know:

Consumer What it does
collect() Gathers items into a collection (Vec, String, HashMap, ...).
sum() / product() Adds or multiplies the items.
count() Counts the items.
fold(init, f) Combines items with an accumulator; the general-purpose consumer.
any(f) / all(f) Short-circuiting yes/no tests.
find(f) The first item matching f, as an Option.
position(f) The index of the first match, as an Option<usize>.
min() / max() Smallest or largest item (Option).
min_by_key / max_by_key Smallest or largest by a derived key.
last() / nth(n) The last item, or the item at position n.
for_each(f) Runs a closure on every item for its side effects.
Rust Consumers in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two points deserve emphasis. First, any, all, find and position short-circuit: they stop pulling items as soon as the answer is known. Second, when you call sum() the compiler often cannot tell the result type on its own, so you must annotate it (let total: i32 = ...) or use the turbofish (.sum::<i32>()).

max() and min() on a tie behave differently: max returns the last of several equal maxima, min the first of several equal minima. For max_by_key the same last-wins rule applies.

max() and min() need the item type to be Ord. f64 is only PartialOrd because of NaN, so floats.iter().max() does not compile. Use fold(f64::MIN, f64::max) or max_by(|a, b| a.total_cmp(b)). See Sorting, Searching and Comparison.

A pipeline, step by step

Here is how the pieces combine. We want the sum of the squares of all even numbers from 1 to 10.

Rust From a for loop to a pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Both versions print 220. Neither is automatically better: loops are fine for complicated control flow. But pipelines state what you want, they cannot go out of bounds, and there is no total to forget to reset.

Performance: iterators are zero-cost

Beginners often worry that chains of closures are slow. In Rust they are not. Each adapter is a small generic struct, closures are inlined, and the optimizer usually fuses the whole chain into a single tight loop, often identical to a hand-written one. Iterating with iter() also skips bounds checks that v[i] would perform on every access. Prefer iterators for clarity; measure only if profiling shows a hot spot.

Common mistakes

  • Forgetting to consume. v.iter().map(...) alone does nothing. Add collect(), sum(), for_each or a for loop.
  • Mixing up item types. iter() yields &T. If a function wants Vec<i32> but you collected Vec<&i32>, add .copied() or .cloned().
  • Using an iterator twice. Most consumers take the iterator by value. After let n = it.count(); the iterator is gone. Clone it first if the iterator is Clone, or recreate it.
  • Modifying a collection while iterating over it. Pushing to a vector inside for x in &v is rejected by the borrow checker, as the next example shows.
Rust Mutating while iterating (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler stops you with error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable. The loop holds a shared borrow of v for its whole duration, so v.push conflicts. Collect the changes first and apply them afterwards, or use retain, drain or an index loop that deliberately re-checks the length. Read about the underlying rule in borrowing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does next() return when an iterator is exhausted?

    next() returns Option<Item>: Some(value) while items remain and None once the iterator is finished. Calling it again keeps returning None for well-behaved iterators.
  2. 2. What is the item type when you loop with for x in v.iter() over a Vec<String>?

    iter() borrows the elements, so each item is &String. into_iter() would yield String and consume the vector, and iter_mut() would yield &mut String.
  3. 3. What does this code print? let it = [1, 2, 3].iter().map(|n| println!("{n}"));

    map returns a new lazy iterator. Without a consumer such as collect(), count() or a for loop, the closure never runs (and rustc warns that the iterator is unused).
  4. 4. Which consumer stops early as soon as it knows the answer?

    any, all, find and position short-circuit. sum, count and collect must visit every item.
  5. 5. Why does vec_of_f64.iter().max() not compile?

    max requires Ord, and f64 only implements PartialOrd. Use max_by(|a, b| a.total_cmp(b)) or a fold with f64::max.

Summary

  • An iterator implements Iterator with an Item type and a next() method returning Option<Item>; a for loop just calls next() until None.
  • iter() yields &T, iter_mut() yields &mut T, into_iter() yields T and consumes the collection.
  • Adapters (map, filter, enumerate, zip, take, skip, chain, rev, peekable) are lazy and do nothing until consumed.
  • Consumers (collect, sum, count, fold, any, all, find, position, min, max) produce the final result; any, all and find short-circuit.
  • Slices add windows and chunks; copied() and cloned() turn references into values.
  • Iterator pipelines compile to the same fast code as hand-written loops.
  • You cannot mutate a collection while a borrowing iterator over it is alive (E0502).

Next: Iterator Patterns and Collecting