In a Rust `&mut self` method, why does `let out = self.pending;` fail with E0507, and when do `mem::take`, `mem::replace` and `mem::swap` fix it?
answer
- a hole behind a reference
- the owner still expects a value
- leave something valid behind
- Default for take, explicit for replace
basics
~20 sMoving a field out through &mut self would leave a hole in a struct its owner still uses, so rustc rejects it with E0507. std::mem::take, replace and swap move the old value out and put a valid value back in the same step.
solid answer
~40 s`self` is only borrowed, so `let out = self.pending;` would move the `Vec` out and leave `self.pending` uninitialised in a struct the caller still owns and will use and drop. rustc reports E0507, "cannot move out of `self.pending` which is behind a mutable reference". The `std::mem` functions move out and refill in one operation: `mem::take(&mut self.pending)` returns the vector and leaves `T::default()`, here an empty `Vec` that does not allocate, so `T` must implement `Default`; `mem::replace(&mut self.tool, Tool::Idle)` leaves the value you pass and works for any `T`, such as a state enum with no sensible default; `mem::swap(&mut a, &mut b)` exchanges two places. For an `Option` field, `self.field.take()` is the method form. None of them needs `Clone`, and none drops either value.
code
rust · 14 linesstruct Node { id: u32 }
struct Editor {
pending: Vec<Node>,
}
impl Editor {
fn flush(&mut self) -> Vec<Node> {
let out = self.pending;
out
}
}
fn main() {
let mut ed = Editor { pending: vec![Node { id: 1 }] };
println!("{}", ed.flush().len());
}go deeper
Recall that you cannot move a field out through a reference and that mem::take leaves a default value behind so the struct stays whole.
Explain E0507 in terms of who owns the struct after the method returns, and pick take, replace, swap or Option::take by what the field can hold.
Use mem::replace to drive enum state machines by value, keep panic windows short after a take, and check that the placeholder does not violate the type's invariants.
When many methods juggle placeholders, consider making them take self by value and return the new state; ownership in the signature is clearer than a struct that is briefly half-valid.
## Why you cannot move out from behind `&mut` A method that takes `&mut self` has **exclusive access** to the struct but does not **own** it. The caller does, and after the method returns the caller will keep using the struct and eventually drop it, which drops every field. If `let out = self.pending;` were allowed, `self.pending` would be left **moved-out**, and the caller's later use or drop would touch a value that no longer exists. Rust has no notion of a temporarily empty field behind a reference, so rustc rejects the move: - **E0507**, "cannot move out of `self.pending` which is behind a mutable reference" - a note that the move occurs because `Vec<Node>` does not implement the `Copy` trait - suggestions to borrow (`&self.pending`) or, if the element type implemented `Clone`, to clone The same error appears for `match self.tool { Tool::Dragging { path, .. } => .. }` when the arm binds a non-`Copy` field by value, and for moving out of a `Vec` element by index. ## The three `std::mem` tools Each one moves the old value out **and** leaves a valid value in its place, in one call that never exposes a hole. | Function | Leaves behind | Requirement | Typical use | |---|---|---|---| | `mem::take(&mut x)` | `T::default()` | `T: Default` | drain a buffer, `Vec`, `String` or `Option` field | | `mem::replace(&mut x, v)` | the value `v` you pass | none | advance an enum state machine, swap in a fresh value | | `mem::swap(&mut a, &mut b)` | each place holds the other's value | same type `T` | exchange undo and redo stacks, double buffers | The standard library's own docs make the point: `take` lets you take ownership of a struct field by replacing it with an "empty" value, and works even when `T` does not implement `Clone`. `replace` neither drops the old value nor the new one; it hands the old one back to you, and is marked `#[must_use]`, because ignoring its result is just an assignment. ## A graph editor's examples 1. **Flushing pending edits.** `fn flush(&mut self) -> Vec<usize> { mem::take(&mut self.pending) }` returns the queued ids and leaves an empty `Vec`. `Vec::new()` does not allocate, so the swap costs no heap traffic. 2. **Finishing a drag.** A `Tool` enum has variants `Idle` and `Dragging { node, path }`, with no `Default`. `mem::take` would fail with E0277 because `Tool: Default` is not satisfied, so `match mem::replace(&mut self.tool, Tool::Idle) { .. }` takes the old state by value, lets the arm move `path` out, and leaves the editor idle. 3. **Undo and redo.** `mem::swap(&mut self.undo, &mut self.redo)` exchanges the two stacks without cloning either. For an `Option<T>` field, `Option::take` (`self.selection.take()`) leaves `None`, and `Option::replace` leaves `Some(value)`; they are the method forms of the same idea. ## What these tools do not change - They are **safe** functions to call: you write no `unsafe`, and the struct is always fully initialised. - If code panics after `take` and before you restore a value, the struct keeps the placeholder. That is memory-safe, but your invariants may now be wrong, so keep the window short. - The placeholder must be meaningful. Taking a `Vec` out of a struct whose invariant is "never empty" breaks the invariant even though it compiles. - When the method can take `self` by value, it **owns** the struct and can move fields out directly, unless the type implements `Drop`, which makes that E0509; the `mem` tools are for `&mut self`. ## Do not wrap fields in `Option` just to take them A common workaround is to declare `tool: Option<Tool>` purely so that `self.tool.take()` compiles. Every other access then needs an `unwrap` or a `match` for a `None` that should never happen outside the method. Prefer an explicit placeholder variant with `mem::replace`, or a method that takes `self` by value and returns the new state, so the type still says what states are possible. ## Choosing - Field type has a natural empty value: `mem::take`. - State machine or no `Default`: `mem::replace` with an explicit placeholder variant. - Two places of the same type trade values: `mem::swap`. - `Option` field: `Option::take`. - Cloning instead only works when `T: Clone` and copies data you are about to discard anyway.
- What happens if you call `mem::take` on a field whose type does not implement `Default`?It does not compile: `mem::take` has a `T: Default` bound, so rustc reports E0277, the trait `Default` is not implemented for the type. Use `mem::replace` with an explicit placeholder, or derive `Default` if a default value is honest for the type.
- If a panic happens between `mem::take(&mut self.pending)` and putting a value back, is the struct in an invalid state?Not in the memory-safety sense: it holds the empty `Vec` that `take` left, which is a valid value, and it will be dropped normally. Logical invariants may be broken, though, so keep the code between taking and restoring short and free of fallible calls where you can.
- When would you write `self.selection.take()` instead of `mem::take(&mut self.selection)`?When the field is an `Option`: `Option::take` is the method form and leaves `None`, exactly what `mem::take` would leave because `Option`'s default is `None`. It reads better and does not need a `std::mem` import.
- You can move a field out of &mut self as long as you assign it back before returning.
- mem::take works for any type, because it leaves the field uninitialised.
- mem::replace drops the old value and returns nothing useful.
- The fix for E0507 is always to derive Clone and clone the field.
- mem::take and mem::replace are unsafe functions.