skip to content

When rustc desugars a Rust `for pattern in expr` loop, which calls does it make, and what does that let you write after `in`?

level: middleimportance: should knowfreq 48%

answer

  1. one call, then a loop
  2. next until None
  3. every Iterator is IntoIterator
  4. temporaries live for the loop

basics

~20 s

rustc turns a for loop into one call to IntoIterator::into_iter(expr) followed by a loop that calls Iterator::next and breaks on None. Anything implementing IntoIterator can follow the in keyword: collections, references to them, ranges, and any iterator, including &mut iter.

solid answer

~40 s

The Reference spells it out: `for PATTERN in iter_expr { body }` becomes a `match IntoIterator::into_iter(iter_expr)` that binds `mut iter`, then a `loop` matching `Iterator::next(&mut iter)`: `Some(val)` binds `let PATTERN = val` and runs the body, `None` breaks. Three consequences. Any `IntoIterator` type works after `in`, and because std has `impl<I: Iterator> IntoIterator for I`, an iterator is accepted and returned unchanged. Because `&mut I` is itself an `Iterator`, `for x in &mut iter` borrows an iterator, so you can `break` and resume it later. And the outer `match` keeps temporaries in `iter_expr` alive for the whole loop. The pattern must be irrefutable, `break` cannot carry a value (E0571), and `..3` is rejected with E0277 because `RangeTo` is not an iterator.

code

rust · 12 lines
rust
fn main() {
    let tasks = vec!["write tests", "review PR"];
    // What `for task in &tasks { println!("{task}"); }` becomes:
    let mut iter = IntoIterator::into_iter(&tasks);
    loop {
        match Iterator::next(&mut iter) {
            Some(task) => println!("{task}"),
            None => break,
        }
    }
    println!("{} tasks still owned", tasks.len());
}

go deeper

for a junior

Recall that a for loop calls into_iter once and then next until None, so anything iterable, including a range or an iterator, can follow in.

for a middle

Explain the blanket IntoIterator impl for iterators and the Iterator impl for &mut I, and use them to resume an iterator after break.

for a senior

Diagnose a lock held for a whole loop by a temporary guard in the header, and know why break with a value is E0571.

for a principal

Use the desugaring as the shared mental model when reviewing loops, so surprises about moves, borrows and guard lifetimes are argued from the rule, not folklore.

## The expansion, as the Reference writes it The Rust Reference gives a `for` loop an exact desugaring. Simplified, `'label: for PATTERN in iter_expr { body }` is equivalent to: ```rust { let result = match IntoIterator::into_iter(iter_expr) { mut iter => 'label: loop { let mut next; match Iterator::next(&mut iter) { Option::Some(val) => next = val, Option::None => break, }; let PATTERN = next; let () = { /* body */ }; }, }; result } ``` Read it in order: 1. **`IntoIterator::into_iter(iter_expr)` runs once.** Whatever follows `in` is converted into an iterator a single time, before the first element. 2. **`Iterator::next(&mut iter)` runs every round.** `Some(val)` continues, `None` ends the loop with `break`. 3. **`let PATTERN = next`** binds each item, so the pattern must be **irrefutable**: `for (i, task) in ...` or `for &n in &numbers` work, while `for Some(x) in ...` does not. 4. **`let () = { body }`** forces the body to evaluate to `()`. `IntoIterator`, `Iterator` and `Option` here are always the standard library's items, never whatever those names mean in the current scope. The names `iter`, `next` and `val` are for exposition only; your code cannot refer to them. ## What may follow `in` Because the first step is `IntoIterator::into_iter`, anything that implements **`IntoIterator`** is accepted: | After `in` | `Item` | Notes | |---|---|---| | `tasks` (a `Vec<Task>`) | `Task` | consumes the vector | | `&tasks`, `&mut tasks` | `&Task`, `&mut Task` | borrows for the loop | | `0..n`, `0..=n` | integer | ranges are iterators | | `tasks.iter()` or any iterator | its `Item` | passed through unchanged | | `&mut iter` | the iterator's `Item` | borrows an iterator so it survives the loop | | `Some(x)`, `Option<T>` | `T` | zero or one round | Two std impls make the iterator rows work. The blanket **`impl<I: Iterator> IntoIterator for I`** returns the iterator itself, so `for x in v.iter()` costs nothing extra. And **`impl<I: Iterator + ?Sized> Iterator for &mut I`** makes a mutable reference to an iterator an iterator too; `Iterator::by_ref` is the method form of the same idea. That is how a loop can stop early with `break` and leave the rest of the sequence for a second loop. ## Consequences you meet in real code - **Temporaries live as long as the loop.** The Reference notes that the outer `match` is there so temporaries in `iter_expr` are not dropped before the loop finishes. In `for t in list.lock().unwrap().iter()`, the `MutexGuard` temporary stays alive, and the lock stays held, until the loop ends; binding a snapshot or the guard to a variable first makes the scope explicit. - **No value from `break`.** A `for` loop always evaluates to `()`, so `break x` inside one is **E0571**, "`break` with value from a `for` loop". Use `loop`, or a consumer such as `find`, when you need a result. - **Non-iterable ranges are E0277.** `for i in ..3` fails with "`RangeTo<{integer}>` is not an iterator", and std's diagnostic suggests adding a start such as `0..3`. - **The loop sees one snapshot of the expression.** `into_iter` is called once, so assigning `n = 10` inside `for i in 0..n` does not extend the range; pushing to a collection you borrowed in the header is rejected by the borrow checker instead. ## Patterns in the header Because each item goes through `let PATTERN = next`, the header can destructure as any `let` can: - `for (i, task) in tasks.iter().enumerate()` splits each `(usize, &Task)` pair; - `for &n in &numbers` copies each `i32` out of its `&i32`, which only works when the item type is `Copy`; - `for mut task in tasks` makes the owned item mutable inside the body; - a refutable pattern such as `Some(x)` is rejected, since `let` requires an irrefutable pattern; use `while let` or `flatten` instead. ## Writing the expansion by hand Seeing the expansion in plain code helps when a loop's behaviour surprises you. Calling `IntoIterator::into_iter(&tasks)` and driving it with `Iterator::next` gives exactly the `&T` items `for task in &tasks` gives, and leaves `tasks` owned afterwards. The same exercise explains why `for task in tasks` moves the vector: the by-value receiver is passed straight into `into_iter`. How an individual adapter such as `map` or `filter` produces its items, and how to write your own `Iterator` impl, are separate subjects; the desugaring only relies on `into_iter` and `next`.

  • Why does `for t in list.lock().unwrap().iter()` keep a `std::sync::Mutex` locked for the whole loop?
    The desugaring wraps `IntoIterator::into_iter(iter_expr)` in an outer `match`, so temporaries created in `iter_expr`, including the `MutexGuard`, live until the loop finishes. Bind the guard or a cloned snapshot to a variable before the loop to make the scope explicit.
  • Why does `let found = for x in &v { if *x == 2 { break x; } };` fail to compile?
    A `for` loop always evaluates to `()`, because it can end by exhausting the iterator without any `break`. rustc rejects `break` with a value inside one as E0571. Use `loop` with `break value`, or an iterator consumer such as `find`, to produce a result.

  • A for loop calls into_iter again at the start of every round.
  • Only collections can follow the in keyword; an iterator must be collected first.
  • for x in &mut iter is the same as moving iter into the loop.
  • Temporaries in the loop header are dropped before the first round.
  • A for loop can return a value with break, just like loop.