Theme
Q016. What is a partial move?
Short Answer
A partial move moves one or more non-Copy fields out of a composite value while leaving other fields available. The whole parent can no longer be used because it is not fully initialized, but untouched fields can still be accessed. Rust tracks initialization per place projection. Types implementing Drop generally cannot have fields moved out this way.
Deep Dive
Struct fields are distinct places. Moving an owned non-Copy field marks that field as moved while leaving unrelated fields initialized:
text
user.name = moved
user.age = initialized
user = partially movedThe remaining fields can be used directly, but operations requiring the complete struct are rejected. Destructuring patterns can combine moves, copies, and borrows: a String field may move, a u32 field may copy, and a field matched with ref may be borrowed.
A type with a custom Drop implementation cannot normally be partially moved because its destructor receives &mut self and may need every field to remain valid.
Internal Model
The compiler tracks places and projections such as user.name and user.age separately. Move paths let drop elaboration destroy only fields that remain initialized.
No runtime partially-moved marker is generally stored in the struct. The state exists in compiler analysis, with drop flags added only when control flow makes runtime state necessary.
Example
rust
struct User {
name: String,
age: u32,
}
fn main() {
let user = User {
name: String::from("Ada"),
age: 36,
};
let name = user.name;
println!("{name}");
println!("{}", user.age);
// println!("{}", user.name); // error: name was moved
}Common Mistakes
- Assuming moving one field always moves every field.
- Trying to use the complete parent after one of its fields moved.
- Assuming every type permits fields to be moved out independently.
Follow-ups
- How do
refandref mutaffect destructuring patterns? - Why does implementing
Droprestrict partial moves? - How does Rust drop the fields remaining after a partial move?
Related
- Q003. What invariants does ownership enforce?
- Q006. What is the difference between an owner, a binding, a value, and a resource?
- Q018. Why can't you move a value out of borrowed or indexed content?
References
- The Rust Programming Language
- Rust Reference
- rustc-dev-guide