Theme
Q011. What is a move in Rust?
Short Answer
A move transfers a value from one place to another. For a non-Copy type, the destination becomes responsible for the value and the source can no longer be used until reinitialized. Moves can occur through assignment, function arguments, returns, patterns, and captures. A move is a semantic rule, not a guaranteed physical memory operation.
Deep Dive
Rust uses move semantics by default for types that do not implement Copy. A move preserves one valid cleanup path: the destination receives the value, while the source place becomes unavailable and will not be dropped.
Common move contexts include:
- binding a value to another variable;
- passing an argument by value;
- returning a value;
- extracting a non-
Copyfield; - matching by value;
- capturing a value in a
moveclosure.
Types implementing Copy behave differently in these contexts: Rust creates an independent value and leaves the source usable.
Internal Model
The compiler records a move in its analysis of places and control flow. It marks the source place as moved from and the destination as initialized. Later reads, borrows, moves, or drops through the old place are rejected.
At runtime, a move may compile to copying bytes, passing registers, reusing storage, or no instructions at all. It does not inherently call Clone, allocate memory, or clear the source bytes.
Example
rust
fn consume(message: String) {
println!("{message}");
}
fn main() {
let message = String::from("ownership");
consume(message); // passing by value moves the String
// println!("{message}"); // error: message was moved
}Common Mistakes
- Describing a move as a deep copy of the underlying resource.
- Assuming moves happen only in
let destination = sourceassignments. - Saying a moved-from value is immediately dropped.
Follow-ups
- What is physically transferred when a
Stringmoves? - How does
Copychange a move context? - Can a moved-from binding be initialized again?
Related
- Q001. What is ownership?
- Q008. How is ownership enforced and represented under the hood?
- Q012. What is physically moved during a Rust move?
References
- The Rust Programming Language
- Rust Reference