skip to content

Why does rustc reject shipping a Rust `Vec<String>` batch from inside a `for` loop with E0382, 'value moved here, in previous iteration of loop'?

level: middleimportance: should knowfreq 52%

answer

  1. the body runs more than once
  2. analysis follows the loop's back edge
  3. a moved-from binding can be reassigned
  4. or create the batch inside
  5. break right after the move

basics

~20 s

rustc follows the loop's back edge: moving batch in one iteration leaves it deinitialised when the next iteration uses it. Reassign batch right after the move, create it inside the loop, or leave the loop after moving it.

solid answer

~40 s

rustc's move analysis follows control flow, and a loop has an edge from the end of its body back to the top. If `ship(batch)` moves `batch` on some path through the body, the next iteration's `batch.push(...)` can reach a deinitialised variable, so rustc reports E0382 and labels the move "value moved here, in previous iteration of loop". Putting the move inside an `if` does not help, because any path counts. The usual fix is to assign a fresh vector right after the move, `batch = Vec::with_capacity(2);`: assigning to a moved-from `let mut` binding is allowed and drops nothing. Alternatives are declaring `batch` inside the loop when it really is per-iteration, leaving with `break` or `return` straight after the move, or `ship(std::mem::take(&mut batch))`. Cloning also compiles but copies every line for nothing.

code

rust · 14 lines
rust
fn ship(batch: Vec<String>) {
    println!("shipped {:?}", batch);
}

fn main() {
    let lines = ["GET /a 200", "GET /b 500", "GET /c 200", "GET /d 404"];
    let mut batch: Vec<String> = Vec::new();
    for line in lines {
        batch.push(line.to_string());
        if batch.len() == 2 {
            ship(batch);
        }
    }
}

go deeper

for a junior

Recognise the 'moved here, in previous iteration of loop' wording and know that a variable declared before a loop is the same variable in every iteration.

for a middle

Explain the back-edge reasoning and pick a repair: reassign after the move, declare the batch inside the loop, or break; know that reassignment needs let mut.

for a senior

In review, reject a clone that only silences this error, and check that the final partial batch is flushed after the loop rather than dropped silently.

for a principal

No lead decision lives here; at this level, show how a batching stage's ownership flow (fill, hand off, start fresh) should read directly off the code.

## How rustc sees a loop The move checker works on the function's **control-flow graph**: blocks of code joined by edges for every way execution can continue. A `for`, `while` or `loop` adds a **back edge** from the end of the body to the top of the next iteration. A variable declared before the loop is one variable for the whole loop, not a fresh one per iteration. So the checker asks, for each use of `batch`: is there any path from a move of `batch` to this use without a reinitialisation in between? In a batching loop there is: 1. Iteration *n* pushes a line, sees the batch is full, and calls `ship(batch)`, which moves it. 2. The back edge returns to the top of the loop. 3. Iteration *n + 1* calls `batch.push(...)` on a variable that no longer owns anything. That path exists in the code, so the program is rejected, whether or not it would run for this particular input. The checker does not evaluate conditions, so wrapping the move in `if batch.len() == 2` changes nothing. ## Why the rule protects you If rustc let this compile, iteration *n + 1* would push into a vector that `ship` now owns. `ship` may already have dropped it, freeing the buffer, or handed it to another stage that is reading it. Either way the next `push` would write into memory the loop no longer owns, a **use after free** or an unsynchronised write. Sole ownership makes that impossible to express: once the batch is shipped, the loop must start a new one before it can push again. ## Reading the diagnostic ```plaintext error[E0382]: borrow of moved value: `batch` 8 | for line in lines { | ----------------- inside of this loop 9 | batch.push(line.to_string()); | ^^^^^ value borrowed here after move 10 | if batch.len() == 2 { 11 | ship(batch); | ----- value moved here, in previous iteration of loop ``` The use that rustc flags (line 9) appears *above* the move (line 11) in the source. That only makes sense once you read the label: the move happened in the previous iteration. When the moving call is itself the repeated use, as in `for _ in 0..2 { sink(b); }`, the headline is `use of moved value` and the same label sits on that single call. ## The repairs | Repair | When it fits | Cost | |---|---|---| | `ship(batch); batch = Vec::with_capacity(2);` | the batch is long-lived and refilled | a fresh vector for the next batch | | `let mut batch = Vec::new();` inside the loop | each iteration builds and finishes its own batch | none | | `ship(batch); break;` or `return` | the loop is done once the batch is shipped | none | | `ship(std::mem::take(&mut batch));` | you want one expression, or `batch` is a field behind `&mut self` | swaps in an empty `Vec` | | `ship(batch.clone());` | almost never | copies every `String`, and `batch` keeps growing | `std::mem::take` moves the contents out and leaves `Default::default()` (an empty `Vec`) behind, so `batch` is never deinitialised. Using it to move out of a borrowed place is a borrow-checker technique; here it is just a convenient one-liner. ## What assignment to a moved-from binding does Reassigning `batch` after the move is legal because a deinitialised variable can be **reinitialised**: the Reference says a moved-from local cannot be read again *until it is reinitialised*. Two details matter: - The binding must be `let mut`. Without `mut`, the second assignment is rejected with E0384, `cannot assign twice to immutable variable`. - The assignment **drops nothing**. Assignment runs the destructor of its left-hand side only if that side is initialised; the shipped vector now belongs to `ship` and is not touched. ## Edge cases worth knowing - `ship(batch); continue;` still fails: `continue` takes exactly the back edge that leads to the next use. - `ship(batch); break;` compiles even with no reassignment, because no path leads from the move back into the loop. - `while let` and `loop` behave the same way as `for`, and so does a loop nested inside another: the inner move is checked against every path back to its own head. - The loop's own item, `line` in `for line in lines`, is a fresh binding every iteration, so moving it in the body is fine. - After the loop, a half-filled batch is still in `batch`. Ship it explicitly, as the runnable example does, or it is silently dropped at the end of the function.

  • Why does `sink(batch); break;` inside the loop compile when `sink(batch); continue;` does not?
    `break` leaves the loop, so there is no path from the move back to the loop head and nothing reads `batch` again. `continue` jumps straight to the next iteration, which is exactly the path that reaches the moved-from variable, so rustc still reports E0382.
  • When is `std::mem::take(&mut batch)` better than reassigning after the move?
    `mem::take` returns the full vector and leaves an empty `Vec` in its place in one expression, so `batch` is never deinitialised. That matters most when `batch` is a field reached through `&mut self`, where moving out is not allowed at all. Reassigning with `Vec::with_capacity(n)` instead lets you choose the new capacity.

  • Each loop iteration gets a fresh copy of variables declared before the loop.
  • Wrapping the move in an if makes rustc accept it.
  • Assigning a new Vec after the move drops the batch that was shipped.
  • Writing continue right after the move tells rustc the variable is not read again.
  • Cloning the batch before shipping it is the idiomatic fix.