The Analogy: The Turnstile And The Gates Bolted In Front Of It
A turnstile hands through one person at a time, and only when somebody pushes. It does not know how long the queue behind it is and it cannot be asked; there is no window in the side reading "forty-one waiting". You push, and either a person comes through or nobody does, and "nobody does" is how you learn the queue is empty. That is the entire contract, and it is deliberately smaller than you might expect.
Bolt a second gate in front of it -- a bag check, say -- and what you have built still behaves like one turnstile. From where you are standing at the far end you cannot tell whether there is one gate in the line or six. You push, and either somebody arrives or the queue is done. The arrangement composes because every piece of it presents the same tiny contract to whatever is downstream of it.
Building the arrangement moves nobody. You can spend all morning bolting six gates together in a row and the queue is precisely where it was when you started; nothing has been checked, nothing has been searched, nobody has moved a step. The gates only do work when somebody at the far end starts pulling. And when they do, one person goes through all six gates before the second person goes through the first -- the line is not six separate operations on the whole crowd, it is one operation repeated per person.
There are three ways to run a hall of people past a gate, and the difference is what the hall looks like afterwards. You can let them through and back to where they were, and the hall is unchanged. You can let them through and let them swap coats on the way, and the hall is still full but altered. Or you can let them out of the building entirely, in which case the hall is empty and asking a second time gets you nothing at all.
Syntax or Core Structure
An iterator is anything that answers one question: what is next?
fn main() {
let readings = vec![18, 24, 7, 31, 24];
let mut it = readings.iter();
println!("{:?}", it.next());
println!("{:?}", it.next());
println!("{:?}", it.next());
println!("{:?}", it.next());
println!("{:?}", it.next());
println!("{:?}", it.next());
for (i, r) in readings.iter().enumerate() {
println!(" {i} -> {r}");
}
println!("count {}", readings.iter().count());
println!("sum {}", readings.iter().sum::<i32>());
println!("max {:?}", readings.iter().max());
}
Output:
Some(18)
Some(24)
Some(7)
Some(31)
Some(24)
None
0 -> 18
1 -> 24
2 -> 7
3 -> 31
4 -> 24
count 5
sum 104
max Some(31)
Six calls to next for five items: the sixth returns None, and that is how the loop above knows to stop. The iterator has to be mut because handing out an item changes it -- an iterator that yields without advancing would yield the same item forever.
The trait behind all of this is remarkably small:
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
One associated type, of the kind Module 6 introduced with type Err, and one required method. Everything else -- count, sum, max, enumerate, zip, fold, all seventy-odd of them -- is a provided method written once in the standard library on top of next. Implement the one method and you inherit the lot.
A for loop is not special syntax over collections. It is this:
let mut it = readings.into_iter();
while let Some(r) = it.next() {
println!("{r}");
}
for x in thing calls thing.into_iter() and then loops on next until it gets None. Which into_iter gets called is decided by what you wrote in the loop header, and that choice is the analogy's fourth paragraph:
| Written as | Each item is | The collection afterwards |
|---|---|---|
v.iter() or for x in &v | &T, a shared borrow | Untouched, still usable |
v.iter_mut() or for x in &mut v | &mut T | Still usable, possibly altered |
v.into_iter() or for x in v | T, owned | Consumed and gone |
Technical Depth: Laziness, Ownership, And Building Your Own
Borrowing, altering, consuming
fn main() {
let mut readings = vec![18, 24, 7, 31];
for r in readings.iter_mut() {
*r += 100;
}
println!("{readings:?}");
let names = vec![String::from("north"), String::from("south")];
let mut widest = 0;
for n in names.into_iter() {
widest = if n.len() > widest { n.len() } else { widest };
}
println!("widest {widest}");
}
Output:
[118, 124, 107, 131]
widest 5
The first loop hands out &mut i32, so *r += 100 writes back into the vector and readings is still there to print. The second hands out owned Strings, each of which is dropped at the end of its turn round the loop, and names cannot be printed afterwards -- there is nothing left to print. Choosing into_iter when iter would have done is the most common way to lose a collection you still wanted.
Nothing happens until you pull
fn main() {
let readings = vec![18, 24, 7, 31, 24];
let pipeline = readings.iter().enumerate().skip(1).take(3);
println!("built, and nothing has happened yet");
for (i, r) in pipeline {
println!(" {i} -> {r}");
}
}
Output:
built, and nothing has happened yet
1 -> 24
2 -> 7
3 -> 31
Three adapters were stacked before that message printed and not one item moved. Iterator is marked #[must_use] precisely because of this: writing readings.iter().skip(1); as a statement compiles, does absolutely nothing, and earns you a warning saying so.
Look at the numbers, too. enumerate came before skip, so the positions are positions in the original sequence and the first one printed is 1. Put the skip first and they would start at 0 again. Order in the chain is not decoration.
One item all the way through, then the next
fn main() {
let ids = vec![7, 8, 9];
for n in ids
.iter()
.inspect(|n| println!("gate A {n}"))
.inspect(|n| println!("gate B {n}"))
{
println!("arrived {n}");
}
}
Output:
gate A 7
gate B 7
arrived 7
gate A 8
gate B 8
arrived 8
gate A 9
gate B 9
arrived 9
This is the fact that makes iterators cheap: the chain is not three passes over the data, it is one pass in which each item visits every stage. Nothing intermediate is stored, so a chain of eight adapters over a million items allocates nothing at all.
The one arrangement that looks like an exception is a skip in the middle. Skipping is done by pulling items and throwing them away, so a .skip(2) between the two gates above would print gate A three times before gate B printed once -- the first two were pulled and discarded, and only the third got through. That is still one pass; it is just a pass in which the discarded items never reach the far end.
Adapters and consumers
| Adapter -- lazy, hands back another iterator | What it does |
|---|---|
enumerate | Pairs each item with its position |
zip | Walks two iterators together, stopping at the shorter one |
take and skip | Keeps the first n, or drops the first n |
rev | Walks backwards, when the source can be walked from both ends |
chain | Runs a second iterator after the first |
step_by | Yields every nth item |
inspect | Hands each item to a closure on the way past, unchanged |
map and filter | Transform and select -- the next two lessons |
| Consumer -- runs the chain and hands back a value | What it does |
|---|---|
next | One item; the only method you must write yourself |
count | How many, by walking every one of them |
sum and product | Adds or multiplies the lot |
min and max | The smallest or largest |
last | Walks to the end and hands back what it found there |
fold | Any accumulation you can express, starting from a value you supply |
any, all, position | Stop the moment the answer is settled |
collect | Builds a collection -- the next lesson |
Walking two things together, and backwards
fn main() {
let bays = ["A1", "A2", "A3", "A4"];
let counts = [12, 0, 7];
for (bay, n) in bays.iter().zip(counts.iter()) {
println!("{bay} {n}");
}
let extra = ["B1"];
for bay in bays.iter().chain(extra.iter()).rev() {
println!("{bay}");
}
println!("every other");
for bay in bays.iter().step_by(2) {
println!(" {bay}");
}
}
Output:
A1 12
A2 0
A3 7
B1
A4
A3
A2
A1
every other
A1
A3
zip stopped after three pairs because counts ran out, and it did so without a word of complaint. That silence is the useful behaviour most of the time and the dangerous one occasionally: a mismatch between two lists that should have been the same length is not an error here, it is a shorter loop.
Answering several questions
fn main() {
let charges = [1250, 0, 875, 4200, 0];
let total = charges.iter().fold(0, |acc, c| acc + c);
let any_zero = charges.iter().any(|c| *c == 0);
let all_small = charges.iter().all(|c| *c < 5000);
let first_zero = charges.iter().position(|c| *c == 0);
let widest = charges.iter().fold(0, |acc, c| if *c > acc { *c } else { acc });
println!("total {total}");
println!("any zero {any_zero}");
println!("all small {all_small}");
println!("first zero {first_zero:?}");
println!("widest {widest}");
}
Output:
total 6325
any zero true
all small true
first zero Some(1)
widest 4200
fold is the general one: it takes a starting value and a closure of the previous lesson's FnMut variety, and every other accumulating consumer is a special case of it. any, all and position differ from the rest in a way that matters on long inputs -- they stop pulling as soon as the answer cannot change, so any on a hundred million items that starts with a match reads exactly one.
Writing your own
struct Countdown {
from: u32,
}
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.from == 0 {
return None;
}
self.from -= 1;
Some(self.from)
}
}
fn main() {
let down = Countdown { from: 4 };
for n in down {
println!("{n}");
}
let c = Countdown { from: 10 };
println!("sum {}", c.take(3).sum::<u32>());
}
Output:
3
2
1
0
sum 24
Eleven lines of implementation, one method, and Countdown is now a full member of the ecosystem: take works on it, sum works on it, for works on it, zip and enumerate and fold work on it. The only methods that do not come free are the ones needing extra promises, such as rev, which requires the separate DoubleEndedIterator trait because walking backwards is not something next alone can do.
Real World Example: Reading A Week Of Meter Readings Without Touching An Index
Seven cumulative readings off a water meter, one per day. Everything anyone wants to know about them is a question about pairs of readings, and not one line below contains i + 1.
fn main() {
let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
let meter: [u32; 7] = [10240, 10240, 10391, 10402, 10688, 10688, 10701];
println!("daily");
for (w, day) in meter.windows(2).zip(days.iter().skip(1)) {
println!(" {day} {}", w[1] - w[0]);
}
let span = meter[meter.len() - 1] - meter[0];
let summed = meter.windows(2).fold(0u32, |acc, w| acc + (w[1] - w[0]));
let flat = meter
.windows(2)
.fold(0, |acc, w| if w[0] == w[1] { acc + 1 } else { acc });
let (worst_day, worst) = meter
.windows(2)
.zip(days.iter().skip(1))
.fold(("", 0), |best, (w, day)| {
let delta = w[1] - w[0];
if delta > best.1 {
(*day, delta)
} else {
best
}
});
let first_flat = meter.windows(2).position(|w| w[0] == w[1]);
let ever_fell = meter.windows(2).any(|w| w[1] < w[0]);
println!("span {span}");
println!("deltas {summed}");
println!("flat days {flat}");
println!("worst {worst_day} at {worst}");
println!("first flat {first_flat:?}");
println!("ever fell {ever_fell}");
println!("readings {}", meter.iter().count());
}
Output:
daily
Tue 0
Wed 151
Thu 11
Fri 286
Sat 0
Sun 13
span 461
deltas 461
flat days 2
worst Fri at 286
first flat Some(0)
ever fell false
readings 7
Six different questions about the same seven numbers, and not one of them does index arithmetic. windows(2) is the piece carrying the weight: it hands out overlapping pairs and it physically cannot run off the end of the slice, which is where the hand-written version of this loop has its off-by-one. The version with a for i in 0..meter.len() header and a meter[i + 1] inside it is the same program with one extra opportunity to panic on the last iteration, and everyone who has written it has written that panic at least once.
span and deltas are computed by two entirely unrelated routes and both say 461. That is not a coincidence -- it is a telescoping sum, and the last reading minus the first is necessarily the total of the steps between them. It is worth printing in real code anyway, because the day the two disagree is the day a reading was inserted, dropped or duplicated somewhere upstream, and a mismatch between two numbers that must be equal is the cheapest data-integrity check there is.
zip with skip(1) is where the labelling gets settled. Window n covers the step from day n to day n + 1, so the label belonging to it is the later day, and days.iter().skip(1) is that sentence written as code. zip stopping at the shorter side is what makes it safe rather than merely convenient: there are six windows and six labels after the skip, and had a day gone missing from days the report would simply have been shorter instead of panicking. The first_flat line shows the other side of the same coin -- it reports Some(0), which is Tuesday, because window indices count pairs and not days. That is exactly the off-by-one the labels exist to absorb, and it is why a raw position from a windows chain should almost never be shown to a user.
Now the limits, and the first one is a genuine defect rather than a rough edge. w[1] - w[0] on u32 underflows the instant a reading goes backwards, which panics in a debug build and wraps to something enormous in release. The program does check for that case -- ever_fell asks exactly the right question -- but it asks it after the loop that would already have crashed, so the check is in the wrong place. A real version tests it first and refuses to report, or uses checked_sub and prints a gap instead of a number. Beyond that: this makes six passes over the data for six answers, which is free over seven readings and six times the memory traffic over a million, and a single fold over a tuple accumulator would answer all of them in one. windows(2) yields nothing at all for a slice of length 1 and panics outright if you ask it for windows of size 0. And there are no dates anywhere in this data, only weekday labels, so nothing at all checks that the seven readings and the seven labels describe the same week.
Common Mistakes
- Building a chain and never consuming it.
readings.iter().skip(1);on a line by itself does nothing whatsoever -- no items move, no work happens -- and the only sign of trouble is a warning that anIteratorwas left unused. Laziness means the chain is a description of work, and a description nobody reads is not work.
- Consuming a collection you still wanted.
for n in namestakesnamesby value, so the next mention of it iserror[E0382]. Writefor n in &nameswhen you only need to look, and reach forinto_iterdeliberately, when handing over ownership is the point.
- Losing count of the layers of reference.
v.iter()on aVec<i32>yields&i32, so a predicate reads|c| *c == 0, and insidepositionoranyon an iterator that already yields references you can end up needing**c. When a comparison will not compile, count the ampersands before you change anything else.
- Calling
nexton an iterator that is notmut. Handing out an item advances the iterator, sonexttakes&mut selfandlet it = v.iter(); it.next();iserror[E0596]. The binding needsmuteven though the collection behind it does not.
- Using
count()wherelen()exists.v.iter().count()walks every element to arrive at a number the slice already knew;v.len()reads it. On aVecthat is a pointless linear scan, and inside a loop it is the difference between linear and quadratic.
- Expecting
zipto object to a length mismatch. It never does. Two lists that were supposed to be the same length and are not produce a shorter loop and no diagnostic at all, which is how half a report goes missing without anything appearing to fail.
- Putting
enumerateon the wrong side of askip.enumerate().skip(2)numbers first and then drops, so the first index you see is2;skip(2).enumerate()drops first and then numbers, so it is0. Both are correct and they answer different questions.
- Reusing an iterator after a consumer took it.
it.count()consumesitby value, so a secondit.next()afterwards is a use-after-move. Iterators are single-use by design, and the fix is usually to call.iter()again rather than to clone anything.
- Confusing
windowswithchunks, and forgetting thatwindows(0)panics.windows(2)over four items gives three overlapping pairs;chunks(2)gives two separate halves. Neither is a substitute for the other, and a window size computed at run time needs checking before use, because zero is a panic rather than an empty iterator.
Best Practices
- Reach for an adapter chain before an index loop.
windows,zip,enumerateandstep_bybetween them replace nearly every hand-rolled index expression, and none of them can walk off the end of anything.
- Pick between
iter,iter_mutandinto_iteron purpose rather than by habit, and let the choice say what the loop intends -- looking, altering, or taking.
- Let
zipdo your alignment instead of indexing two slices with the same variable. When the two really must be the same length, check that before zipping, becausezipitself will not tell you.
- Prefer the short-circuiting consumers when the question allows it.
anyandpositionstop the moment they know; counting matches and comparing to zero walks the whole input to learn the same thing.
- Bind a long chain to a
letwith a noun for a name. A pipeline calledrecent_faultsreads as a thing; the same eight adapters inline in aforheader read as a puzzle.
- Implement
Iteratorfor your own sequences rather than exposing an index and a length. Onenextmethod buys the whole standard library, and callers then compose with your type exactly as they would with aVec.
- Count your passes when the input is large. Six consumers is six walks over the data, and one
foldover a tuple accumulator collapses them into one -- worth doing at a million rows, not worth the loss of clarity at seven.
- Use
len()on anything that knows its own length and savecount()for iterators that genuinely have to be walked.
Practice Exercises
- Rewrite the daily-delta loop from the meter example using
for i in 0..meter.len()and indexing, so that it produces byte-for-byte the same output. Then list every line in your version that could panic on a bad input and say which of themwindows(2)andziphad removed for you.
- Replace all six consumers in the meter example with one
foldwhose accumulator is a tuple holding the running total, the flat-day count, and the worst day and its delta. Produce the same output, then explain in two sentences what you gave up in readability to gain the single pass.
- Implement
Iteratorfor astruct Fib { a: u64, b: u64 }yielding Fibonacci numbers, and print the sum of the first ten withtake(10).sum::<u64>(). Say what happens if you callsumwithout thetake, and whycount()on it is a bug rather than a slow operation.
- Change the Saturday reading in the meter example to
10500so the meter appears to run backwards, and record exactly whatcargo testandcargo run --releaseeach do withw[1] - w[0]. Then fix it twice: once by moving theever_fellcheck above the loop, and once by usingchecked_suband printing a gap marker for the bad pair.