skip to content

In a Rust graph editor, why does `nodes.push(..)` inside `for node in &nodes` fail with E0502, and how do you fix it without cloning?

level: middleimportance: must knowfreq 72%

answer

  1. the loop holds the borrow
  2. the iterator is used every pass
  3. a push may reallocate
  4. collect first, or loop over indices

basics

~20 s

A for loop over &nodes keeps a shared borrow alive for the whole loop, because its iterator is advanced on every pass, and push needs &mut nodes and may reallocate. Collect the changes and apply them after the loop, or loop over indices.

solid answer

~40 s

`for node in &nodes` calls `IntoIterator::into_iter(&nodes)`, producing a `std::slice::Iter` that points into the vector's buffer and is advanced on every pass, so the shared borrow is live from the loop header to the last iteration. `nodes.push(..)` needs `&mut nodes`, and a push may reallocate the buffer the iterator is walking, so rustc rejects it with E0502; with `nodes.iter_mut()` the same code is E0499, two mutable borrows. rustc's diagnostic even suggests the fixes: "consider using an index-based loop instead, or collecting modifications into a separate collection". Collecting means building a `Vec<Node>` of additions with `iter().filter().map().collect()` and calling `nodes.extend(additions)` after the loop. An index loop, `for i in 0..nodes.len()`, touches `nodes[i]` in short borrows; the range is computed once, so nodes pushed during the loop are not visited.

code

rust · 14 lines
rust
#[derive(Debug)]
struct Node {
    id: u32,
    children: Vec<u32>,
}
fn main() {
    let mut nodes = vec![Node { id: 1, children: vec![] }, Node { id: 2, children: vec![] }];
    for node in &nodes {
        if node.children.is_empty() {
            nodes.push(Node { id: node.id + 100, children: vec![] });
        }
    }
    println!("{}", nodes.len());
}

go deeper

for a junior

Recall that a for loop over &nodes borrows the vector for the whole loop and that collecting changes or looping over indices are the two standard fixes.

for a middle

Explain the iterator behind the loop, why a push could reallocate under it, and the E0502 versus E0499 split between iter and iter_mut.

for a senior

Choose the fix by semantics: snapshot additions, in-pass updates, or removal with retain, and explain two-phase borrows when a reviewer asks why nodes.push(nodes.len()) is fine.

for a principal

If many passes need to add, remove and re-link nodes while walking, question the data shape rather than adding more index loops; stable ids and a single owner make these passes routine.

## What the loop really borrows The Rust Reference defines `for PATTERN in iter_expr { body }` as a `loop` around `Iterator::next(&mut iter)`, where `iter` is `IntoIterator::into_iter(iter_expr)`. For `for node in &nodes`, that iterator is a `std::slice::Iter<'_, Node>`: a cursor into the vector's heap buffer. It is used again at the top of **every** iteration, so the shared borrow of `nodes` it carries is live for the entire loop, not only while `node` is in use. Inside the body, `nodes.push(Node { .. })` auto-borrows `&mut nodes`. That is a mutable borrow requested while a shared one is live, so rustc reports: - **E0502**, "cannot borrow `nodes` as mutable because it is also borrowed as immutable" - a note that "this for loop borrows `nodes` immutably, preventing mutation within its body" - `help: consider using an index-based loop instead, or collecting modifications into a separate collection` ## Why the rule is not pedantry A `Vec` that is full reallocates on `push`: it allocates a larger buffer, moves the elements and frees the old one. The iterator's pointers would then point into freed memory. In languages without this check the same bug appears as iterator invalidation or a concurrent-modification error at run time; rustc rejects it before the program runs. It rejects it even when the vector has spare capacity and this particular push would not reallocate: the check is static, and capacity is a run-time fact the borrow checker does not see. | Loop header | Borrow held by the loop | `nodes.push(..)` in the body | |---|---|---| | `for node in &nodes` | shared | E0502 | | `for node in nodes.iter_mut()` | mutable | E0499 (second mutable borrow) | | `for node in nodes` | none; the vector is moved into the loop | E0382, use of a moved value | | `for i in 0..nodes.len()` | none after the range is built | compiles | ## Fix 1: collect, then apply Read under the shared borrow, write after it ends: 1. Iterate with `nodes.iter()` and compute what should change (`filter`, `map`). 2. `collect()` the additions into a new `Vec<Node>`; this allocates only the new nodes and clones nothing. 3. After the loop, `nodes.extend(additions)` takes `&mut nodes` with no borrow left to conflict. This shape is the clearest when changes depend only on the state before the pass, and it makes the pass's semantics explicit: new nodes are not themselves examined. ## Fix 2: loop over indices `for i in 0..nodes.len()` evaluates `nodes.len()` once; the `Range<usize>` it produces does not borrow `nodes`. Each `nodes[i]` is a short borrow that ends at its last use, so reading `nodes[i].id` into a local and then calling `nodes.push(..)` is fine. Two consequences matter: - Elements pushed during the loop are **not visited**, because the range was fixed at the start. Use `while i < nodes.len()` if they should be. - Holding `let n = &nodes[i];` across the push brings the error back; copy out the fields you need first. For **removal** while iterating, neither fix is needed: `nodes.retain(|n| ..)` keeps the elements for which the closure returns `true` in one call. ## Why `nodes.push(nodes.len())` compiles It looks like the same conflict: `push` auto-borrows `&mut nodes` and the argument reads `nodes`. It compiles because of **two-phase borrows**: the mutable auto-borrow of a method receiver is first *reserved*, behaving like a shared borrow while the arguments are evaluated, and only *activated* as a mutable borrow when the call starts. The rule is narrow: - it covers compiler-inserted borrows, such as a method receiver's auto-borrow and the implicit reborrow of a `&mut` argument; - `Vec::push(&mut nodes, nodes.len())`, with the `&mut` written out, is E0502; - an argument that itself needs `&mut`, as in `nodes.push(nodes.pop().unwrap())`, is E0499, and rustc suggests storing the argument in a local first. ## Choosing between the fixes - Additions computed from a snapshot: **collect, then extend**. - Updates that depend on earlier updates in the same pass: **index loop**. - Filtering out nodes: **`retain`**. - Editing fields of existing nodes with no structural change: `for node in nodes.iter_mut()` is exactly right, because only the vector's length and buffer are off limits. - Reaching for `nodes.clone()` to iterate a copy works, but copies every node to add a few; treat it as the last option, not the first.

  • Why does `nodes.push(nodes.len())` compile when the loop version does not?
    Two-phase borrows: the `&mut nodes` auto-borrow for the method receiver is only reserved while arguments are evaluated, so `nodes.len()` may read `nodes`; it becomes a real mutable borrow when the call begins. In the loop, the iterator's shared borrow is live across the whole call, so there is no such window.
  • When would you choose the index loop over collect-then-extend?
    When a step must see the effect of earlier steps in the same pass, or when the change is an in-place update of `nodes[i]` rather than an addition. Collect-then-extend reads a snapshot, which is simpler to reason about when that is what you want.
  • What does `nodes.push(nodes.pop().unwrap())` report, and how do you fix it?
    E0499: the argument needs its own `&mut nodes` while the receiver's mutable borrow is reserved, and two-phase borrows only allow shared reads in that window. Store `let last = nodes.pop().unwrap();` in a local, then call `nodes.push(last)`.

  • The loop only borrows nodes while the current node variable is in use.
  • Cloning the whole vector is the standard fix for mutating while iterating.
  • for node in nodes.iter_mut() makes push inside the loop legal.
  • An index loop also visits the nodes pushed during the loop.
  • nodes.push(nodes.len()) compiles because len returns a copy, not because of two-phase borrows.