Theme
Q013. What happens to the source binding after a move?
Short Answer
After a non-Copy value is moved, the source binding can remain lexically in scope, but its place is considered moved from and therefore unusable. Rust prevents reading, borrowing, moving, or explicitly dropping it again. Its destructor does not run through the source; cleanup responsibility follows the value to the destination.
Deep Dive
A move changes initialization state, not lexical scope. The source name still exists, which is why the compiler can report that it was used after move, but it no longer denotes an available value.
Rust rejects operations that require an initialized source:
- reading or formatting it;
- borrowing it with
&sourceor&mut source; - passing or assigning it by value again;
- calling
drop(source).
If the binding is mutable, it can be assigned a new value. That initializes the place again; it does not recover or copy back the original value.
Internal Model
The compiler marks the source place as moved in its dataflow state. The old bytes may physically remain in memory, but safe code cannot observe them as the old value.
Drop elaboration does not emit cleanup for the moved-from source. The value is eventually dropped through its destination unless ownership moves again or destruction is otherwise suppressed.
Example
rust
fn main() {
let source = String::from("rust");
let destination = source;
println!("{destination}");
// println!("{source}"); // error: borrow of moved value
// drop(source); // error: use of moved value
}Common Mistakes
- Saying the source binding disappears from the scope.
- Assuming Rust zeroes or nulls the source at runtime.
- Expecting the moved-from source to run
Dropindependently.
Follow-ups
- Can a moved-from binding be reinitialized?
- How does a partial move affect the remaining fields?
- Why does C++ allow some operations on moved-from objects?
Related
- Q003. What invariants does ownership enforce?
- Q008. How is ownership enforced and represented under the hood?
- Q014. Can a moved binding be reinitialized?
References
- The Rust Programming Language
- Rust Reference
- rustc-dev-guide