In Rust, why is `batch` unusable after `if overflow { archive(batch); }`, and how does the compiled program know whether to drop `batch` at scope end?
answer
- maybe moved counts as moved
- conditions are not evaluated
- reinitialise on the moving path
- a hidden flag on the stack
- only where state is not static
basics
~20 srustc treats a value moved on any path as moved, so a later use fails with E0382 even under if false. Where a local's state is unknown statically, a hidden stack drop flag decides at scope end whether to drop it.
solid answer
~50 sMove checking follows every path but does not evaluate conditions: after `if overflow { archive(batch); }` there is a path on which `batch` was moved, so `batch.len()` is rejected with E0382, even when the condition is the literal `false`. Repairs: reinitialise on the moving path (`archive(batch); batch = Vec::new();` with `let mut`), give each branch its own use or move (`if overflow { archive(batch) } else { println!("{}", batch.len()) }`), or pass a borrow. Dropping is a run-time question here, so the compiler keeps a **drop flag**: hidden state on the stack, updated when `batch` moves and checked when the scope ends, so the vector is freed exactly once, inside `archive` on one path and at the end of `main` on the other. Where the state is known statically, as in straight-line code, no flag is needed.
code
rust · 12 linesfn archive(batch: Vec<String>) {
println!("archived {}", batch.len());
}
fn main() {
let batch = vec![String::from("GET /a 500")];
let overflow = std::env::args().count() > 1;
if overflow {
archive(batch);
}
println!("{}", batch.len());
}go deeper
Know that a value moved inside an if counts as moved after the if, whichever branch actually ran.
Explain that the checker reasons about every path without evaluating conditions, and repair the code by reinitialising on the moving path or restructuring the branches.
Explain drop flags: when a local's initialisation depends on run-time control flow, a stack flag makes its destructor run exactly once, and you can predict where a Drop side effect fires on each path.
No lead decision lives here; at this level, treat a maybe-moved value in review as a sign that the function should make ownership explicit on each branch.
## Possibly moved means moved rustc's move checker walks every path through a function and tracks, for each local, whether it is **initialised**, **moved**, or **maybe moved** (moved on some paths and not others). A use is accepted only if the variable is initialised on *every* path that reaches it. After ```rust if overflow { archive(batch); } println!("{}", batch.len()); ``` one path reaches the `println!` with `batch` moved, so rustc reports "error[E0382]: borrow of moved value: `batch`" and points at the `archive(batch)` call. The checker does **not evaluate conditions**: the same error appears with `if false`, because the analysis looks at the shape of the code, not at values. ## Repairs that satisfy the checker 1. **Reinitialise on the moving path.** With `let mut batch`, write `archive(batch); batch = Vec::new();` inside the `if`. Every path reaching the later use now has an initialised `batch`. 2. **Give each branch its own fate.** `if overflow { archive(batch) } else { println!("{}", batch.len()) }` moves on one branch and uses on the other; nothing after the `if` touches `batch`. 3. **Borrow instead of moving** when `archive` only reads: `fn archive(batch: &[String])`. 4. **Clone** only when two independent copies are really needed; it is a cost, not a fix. ## Drop flags: deciding at run time A second question hides behind the first. When `main` ends, should it drop `batch`? On the path where `archive` ran, the vector was already dropped inside `archive`, and dropping it again would free the buffer twice. On the other path, `main` still owns it and must free it. One compiled `main` has to handle both. The Rustonomicon describes the answer: Rust tracks whether a variable should be dropped **at run time** when it cannot tell statically. As a variable becomes initialised and deinitialised, a hidden **drop flag** for it is toggled; at the point where it might need dropping, the flag is checked. The flags are kept on the stack, beside the locals they describe. You can watch this with a type that prints in its `Drop` implementation, as in the runnable example. Without a command-line argument, `archive` is skipped and the drop message appears after `end of main`. With one, the message appears inside the `archive` call, before `end of main`, and nothing is printed at the end of `main`. ## When the compiler needs a flag | Code shape | Initialisation state known statically? | Drop flag needed? | |---|---|---| | `let b = ...; archive(b);` with no branch | yes: moved | no | | `if c { archive(b); }` | no: depends on `c` | yes | | `if c { archive(b) } else { drop(b) }` | yes: moved on both paths | no | | `let x; if c { x = Box::new(0); }` | no: initialised on one path | yes | The last row is the Rustonomicon's own example: a variable declared uninitialised and assigned in only one branch also needs a flag, because at scope end it might or might not hold a value. When the state is known at every point, there is nothing to decide at run time, so no flag is required. ## Why it matters in production code - **Where a destructor runs depends on the path.** A `Drop` that flushes a file or returns a pooled connection fires inside the callee on one path and at the caller's closing brace on the other. Knowing that predicts the order of side effects. - **Drop flags are small.** They are hidden values on the stack, and none is needed where a local's state is known statically. In old Rust versions they were stored in a hidden field of types that implement `Drop`; today they are tracked on the stack. - **A maybe-moved variable is a design smell.** It usually means a function has not decided who owns the value on each branch. Rewriting the branches so each one clearly moves or keeps the value removes both the E0382 and the need for a flag. - **Partial moves follow the same logic.** The Reference states that after a partial move only the remaining fields are dropped, so no field is freed twice.
- Where does a `Drop` side effect run on each path in the conditional-move example?If `archive(batch)` runs, its parameter owns the batch and drops it when `archive` returns, before the rest of `main` continues. If it does not run, `main` still owns the batch and drops it at its closing brace. The drop flag is what lets one compiled `main` handle both cases.
- Why does rustc reject the use even when the condition is the literal `false`?Move checking is a static analysis over the shape of the control-flow graph; it does not evaluate expressions, including constant ones. An `if false` block is still a path on which `batch` is moved, so the later use is reported as E0382 like any other conditional move.
- rustc rejects the later use only when the moving branch actually runs.
- An if false block is ignored by the move checker, so the use compiles.
- On the path where archive ran, batch is dropped twice, once in each function.
- Drop flags are stored inside every value whose type implements Drop.
- The only fix is to clone batch before the conditional call.