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:
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:
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:
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. |
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.
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
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:
filterpasses its closure a reference to the item, so withiter()over&strthe closure receives a reference to a reference. Auto-dereferencing in method calls such asw.len()hides this, but a comparison like*w == "date"needs explicit dereferences. When types get confusing,.copied()or.cloned()beforefilterstrips a level of reference.rev()needs an iterator that can run from both ends (aDoubleEndedIterator). Ranges, slices and vectors can; many others cannot.zipstops as soon as either side ends, so mismatched lengths never panic.copied()turns an iterator of&Tinto one ofTforCopytypes;cloned()does the same by cloning, for exampleVec<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).
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. |
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.
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. Addcollect(),sum(),for_eachor aforloop. - Mixing up item types.
iter()yields&T. If a function wantsVec<i32>but you collectedVec<&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 isClone, or recreate it. - Modifying a collection while iterating over it. Pushing to a vector inside
for x in &vis rejected by the borrow checker, as the next example shows.
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. What does
next()return when an iterator is exhausted?next()returnsOption<Item>:Some(value)while items remain andNoneonce the iterator is finished. Calling it again keeps returningNonefor well-behaved iterators. -
2. What is the item type when you loop with
for x in v.iter()over aVec<String>?iter()borrows the elements, so each item is&String.into_iter()would yieldStringand consume the vector, anditer_mut()would yield&mut String. -
3. What does this code print?
let it = [1, 2, 3].iter().map(|n| println!("{n}"));mapreturns a new lazy iterator. Without a consumer such ascollect(),count()or aforloop, the closure never runs (and rustc warns that the iterator is unused). -
4. Which consumer stops early as soon as it knows the answer?
any,all,findandpositionshort-circuit.sum,countandcollectmust visit every item. -
5. Why does
vec_of_f64.iter().max()not compile?maxrequiresOrd, andf64only implementsPartialOrd. Usemax_by(|a, b| a.total_cmp(b))or afoldwithf64::max.
Summary
- An iterator implements
Iteratorwith anItemtype and anext()method returningOption<Item>; aforloop just callsnext()untilNone. iter()yields&T,iter_mut()yields&mut T,into_iter()yieldsTand 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,allandfindshort-circuit. - Slices add
windowsandchunks;copied()andcloned()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).
Track your progress
Create a free account to tick off lessons and pick up where you left off on any device.
of Rust lessons completed