skip to content

Moves and Partial Moves

Assigning, passing or returning a non-Copy value moves it and the old binding becomes unusable. Interviewers ask what a move leaves behind and how partial moves work.

on this pageshow

questions

5

In Rust, after `let staged = batch;` or `archive(batch)` with a `Vec<String>`, why is `batch` unusable, and how does ownership come back?

level: juniorimportance: must knowfreq 82%

answer

  1. one owner at a time
  2. Vec<String> is not Copy
  3. the source binding is deinitialised
  4. E0382: use or borrow of moved value
  5. return it, or lend a borrow

basics

~20 s

A Vec<String> is not Copy, so a let or a by-value call moves it: the new binding becomes the only owner and the old one is deinitialised, so any later use fails with E0382. Ownership comes back only as a return value.

solid answer

~40 s

Rust gives every value exactly one owner. `Vec<String>` does not implement `Copy`, so `let staged = batch;` and `archive(batch)` **move** it: the vector's header (pointer, length, capacity) is copied bitwise, the heap buffer is not touched, and `batch` is deinitialised. Any later read is rejected at compile time with E0382 (`borrow of moved value` or `use of moved value`), which is what stops two owners from freeing one buffer. Ownership comes back only if the callee returns it, as in `fn tag(batch: Vec<String>) -> Vec<String>` called as `let batch = tag(batch);`. When a function only reads or edits the batch, the idiomatic signature takes `&[String]` or `&mut Vec<String>` instead, so ownership never changes hands.

code

rust · 10 lines
rust
fn archive(batch: Vec<String>) -> usize {
    batch.len()
}

fn main() {
    let batch = vec![String::from("GET /health 200"), String::from("GET /login 302")];
    let staged = batch;
    let n = archive(staged);
    println!("{n} {}", staged.len());
}

go deeper

for a junior

Recall the three ownership rules and say plainly that a by-value let, call or return moves a non-Copy value, leaving the source unusable, with E0382 as the error.

for a middle

Explain what physically moves (the pointer, length and capacity, not the heap data) and choose between slice, mutable-reference and by-value signatures by what the function does with the batch.

for a senior

Read an E0382 diagnostic in a pull request and pick the fix that matches intent: borrow when the callee only reads, return ownership when it transforms, and challenge a clone that only silences the error.

for a principal

No lead decision hangs on the move rule itself; at this level, explain to reviewers why a by-value parameter is an API promise that the function consumes or stores what it is given.

## The ownership rules behind a move The Rust Book states three **ownership rules**: - Each value in Rust has an **owner**. - There can be only **one owner at a time**. - When the owner goes out of scope, the value is **dropped** (its memory and resources are released). A **move** is how the second rule survives assignment and function calls. A `Vec<String>` owns a heap buffer, and each `String` in it owns its own heap bytes. If two variables could both own that vector, both would try to free the same memory when they went out of scope. So Rust transfers ownership instead of sharing it, and the variable you moved from stops counting as initialised. This only applies to types that do not implement `Copy`. Integers, `bool`, `char` and other `Copy` types are duplicated on assignment and the source stays usable; which types qualify, and why, belongs with Copy and Clone. ## What `let`, a call and a return actually do | Construct | What happens to `batch` | Who owns the vector afterwards | |---|---|---| | `let staged = batch;` | moved, `batch` deinitialised | `staged` | | `archive(batch)` with `fn archive(batch: Vec<String>)` | moved, `batch` deinitialised | the parameter inside `archive`; dropped when `archive` returns unless it is returned | | `return batch` or a tail expression `batch` | moved out of the function | the caller's binding | | `archive(&batch)` with `fn archive(batch: &[String])` | borrowed, unchanged | still `batch` | Physically, a move copies only the bytes of the value itself. For a `Vec<String>` those are three machine words: the pointer to the buffer, the length and the capacity (24 bytes on a 64-bit target, which `std::mem::size_of::<Vec<String>>()` confirms). The buffer and the strings it points to stay exactly where they are, and the optimiser may remove even the 24-byte copy. What makes it a move rather than a shallow copy is that the compiler **invalidates the source**: the Reference says that after moving out of a local variable, the location is deinitialised and cannot be read until it is reinitialised. ## Reading E0382 Using the moved-from variable is a compile error, never a run-time crash: ```plaintext error[E0382]: borrow of moved value: `staged` 7 | let staged = batch; | ------ move occurs because `staged` has type `Vec<String>`, which does not implement the `Copy` trait 8 | let n = archive(staged); | ------ value moved here 9 | println!("{n} {}", staged.len()); | ^^^^^^ value borrowed here after move ``` The three labels tell the whole story: the type is not `Copy`, here is where it moved, here is where you used it again. The headline says `borrow of moved value` when the later use borrows (a `&self` method such as `len`) and `use of moved value` when it tries to move or copy the value again. rustc also suggests the two classic exits: change the parameter to borrow, or call `.clone()`. ## Getting ownership back, or never giving it away Choose the signature by what the function does with the batch: 1. **Only reads it** (counting, validating, formatting): take `&[String]` or `&Vec<String>`. The caller keeps ownership and keeps using the vector. 2. **Edits it in place** (tagging, sorting, deduplicating): take `&mut Vec<String>`. Still no ownership change. 3. **Transforms and hands it back** in a pipeline: take `Vec<String>` and return `Vec<String>`. The caller writes `let batch = tag(batch);`, which shadows the moved-from name with the returned vector. 4. **Consumes or stores it** (pushes it to the next stage, keeps it in a struct): take `Vec<String>` and do not return it. Here the move is the point, and the caller losing access is correct. 5. **Needs an independent duplicate**: call `.clone()`, paying for a copy of every string. That is a deliberate cost, not a way to silence E0382. A by-value parameter is part of an API's contract: it tells callers the function takes over the value. ## What a move is not - It is **not a deep copy**: no element is duplicated, and only an explicit `clone()` does that. - It is **not a reference**: the new owner is fully independent and the old name is dead, not an alias. - It is **not checked at run time**: the whole analysis happens in the compiler, so a compiled program carries no move checks. - It does **not depend on `mut`**: declaring `mut batch` in the callee's parameter only lets the callee mutate the vector it now owns; the caller's variable is gone either way.

  • Does `let batch = tag(batch);` reuse the moved-from variable?
    No. It declares a new binding that shadows the old one. The original `batch` was moved into `tag`; the vector `tag` returns is bound to a fresh `batch` with the same name, so code below sees a valid, owned vector. Shadowing is a common way to thread ownership through a chain of by-value stages without inventing new names.
  • Does moving a value always cost a copy of its bytes?
    Semantically a move is a bitwise copy of the value's own bytes, 24 bytes for a `Vec<String>` on a 64-bit target, and it never touches the heap buffer. The optimiser may build the value in its final place and remove the copy. A large inline value, such as a big array, really is copied byte by byte when it moves, which can show up in profiles.
  • What happens to the vector when `archive(batch)` returns without handing it back?
    Inside `archive`, the parameter is the owner, so the vector and every `String` in it are dropped when the function body ends. The caller cannot see or reuse it: the move transferred the duty to free the memory together with the value.

Handing over the only key to a storage unit: once the next stage holds the key, you can no longer open the unit, and clearing it out is now the holder's job. Lending the key for an afternoon, a borrow, is a different deal, because it comes back to you.

  • After let b = a, both bindings own the same Vec and either can be used.
  • Moving a Vec copies every String in it to the new owner.
  • Use after move is caught at run time with a panic.
  • Declaring the parameter mut lets the caller keep using the moved value.
  • The only fix for E0382 is calling clone() where the move happens.
open as a page

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%

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.

open as a page

In Rust, why does `match cfg.token { Some(t) => ..., None => ... }` leave that `Option<String>` field unusable, and how do you match without moving?

level: middleimportance: should knowfreq 55%

basics

~20 s

The pattern Some(t) binds t by value, so the String moves out of the Option and cfg.token is partially moved; later use fails with E0382 whichever arm ran. Match on &cfg.token or use cfg.token.as_deref() to borrow instead.

open as a page

In Rust, after `let endpoint = cfg.endpoint;` moves one `String` field out of a `Config` struct, what can you still do with `cfg`?

level: middleimportance: should knowfreq 48%

basics

~20 s

Rust tracks moves per field: cfg's other fields stay readable, borrowable and movable, but any use of cfg as a whole fails with E0382 until the moved field is reassigned. A struct that implements Drop forbids the partial move (E0509).

open as a page

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?

level: seniorimportance: should knowfreq 32%

basics

~20 s

rustc 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.

open as a page