Sub topic 11
Owned fields and moves out of structs
This chapter assumes you know Rust's move rules, the difference between & and &mut, and the Copy and Clone traits. It also assumes you have seen impl blocks and the three self receivers. Here we look at what happens to ownership when you take a field out of a struct, and why the compiler accepts some of those moves and rejects others.
Structs own their fields
A field of type String, Vec<T>, or Box<T> is owned by the struct that contains it. The struct is the only owner of that value. When the struct is dropped, each field is dropped too, in declaration order.
This has two consequences:
- Moving a struct moves all its fields with it.
- Reading a field out of a struct is a move unless the field's type is
Copy.
Fields like u32 or bool are copied. Fields like String are moved. The rest of the chapter follows from that difference.
Partial moves
Rust tracks moves per field, not only per variable. You can move one field out of a struct and keep using the others.
#[derive(Debug)]
struct User {
name: String,
email: String,
logins: u32,
}
fn main() {
let user = User {
name: String::from("Ada"),
email: String::from("[email protected]"),
logins: 3,
};
let name = user.name; // partial move: `name` field is now moved out
println!("{name}");
println!("{}", user.email); // still valid
println!("{}", user.logins); // still valid
// println!("{:?}", user); // error: borrow of partially moved value
}After the move, user.name is unusable. The whole user also can't be used as a unit, because {:?} would need to read the moved field. You can still use the other fields individually.
When user goes out of scope, the compiler drops only the fields that are still initialized. It tracks this at compile time, so there is no runtime cost.
Partial moves work on local variables and on owned values. They do not work through references, and that is the more common source of errors.
Moving out of a borrow
Consider a getter that returns an owned String:
struct User {
name: String,
}
impl User {
fn name(&self) -> String {
self.name // error[E0507]: cannot move out of `self.name` which is behind a shared reference
}
}With &self, the caller still owns the User and expects it to be intact afterwards. If the method moved name out, the caller's struct would hold a field with no valid value, and a later drop would free the same heap memory twice. The compiler rejects the move.
The same rule applies to &mut self. A mutable borrow lets you change a field, but it does not let you leave the field empty when the method returns.
Choosing a fix
The right fix depends on what the caller needs.
| Goal | Technique | Cost |
|---|---|---|
| Read the value | Return a reference, such as `&str` or `&String` | None |
| Get an independent copy | `.clone()` | Allocation and copy |
| Take the value and leave a default behind | `std::mem::take` | None; needs `Default` |
| Take the value and leave a chosen one behind | `std::mem::replace` | None |
| Take an optional value and leave `None` | `Option::take` | None |
| Take the value and give up the struct | Method with `self` | None |
Borrow instead of move
Most getters should return a reference. This is the form used in the privacy example from the plan, fn owner(&self) -> &str. The caller can read the data, and ownership stays with the struct.
Swap in a replacement
std::mem::take moves a value out through a &mut reference and puts Default::default() in its place. The field is never left empty, so the compiler accepts it. std::mem::replace does the same but lets you choose the replacement.
use std::mem;
#[derive(Debug)]
struct Buffer {
data: Vec<u8>,
label: String,
}
impl Buffer {
fn new(label: &str) -> Self {
Self {
data: Vec::new(),
label: label.to_string(),
}
}
fn push(&mut self, byte: u8) {
self.data.push(byte);
}
// Hand the bytes to the caller and leave an empty Vec behind.
fn drain_all(&mut self) -> Vec<u8> {
mem::take(&mut self.data)
}
// Return the old label and store the new one.
fn relabel(&mut self, new_label: String) -> String {
mem::replace(&mut self.label, new_label)
}
}
fn main() {
let mut buf = Buffer::new("first");
buf.push(1);
buf.push(2);
let bytes = buf.drain_all();
println!("{:?}", bytes);
println!("{:?}", buf);
let old = buf.relabel(String::from("second"));
println!("{old} -> {}", buf.label);
}This prints [1, 2], then the buffer with an empty data, then first -> second.
Use Option::take for optional fields
When a field is an Option<T>, Option::take moves the value out and leaves None. This is common for fields that are meant to be consumed once.
struct Task {
name: String,
payload: Option<String>,
}
impl Task {
fn run(&mut self) -> String {
match self.payload.take() {
Some(data) => format!("{} processed {}", self.name, data),
None => format!("{} had nothing to do", self.name),
}
}
}
fn main() {
let mut task = Task {
name: String::from("job-1"),
payload: Some(String::from("report.csv")),
};
println!("{}", task.run());
println!("{}", task.run());
}The first call finds the payload. The second finds None, which shows that the value really left the struct.
Consume the struct
A method that takes self owns the whole struct, so it may move any field out. This is why into_dimensions(self) in the Rectangle example is allowed. Naming such methods into_* is a standard convention. You can also destructure self in one step.
struct User {
name: String,
email: String,
logins: u32,
}
impl User {
fn into_contact(self) -> (String, String) {
let User { name, email, .. } = self;
(name, email)
}
}
fn main() {
let user = User {
name: String::from("Ada"),
email: String::from("[email protected]"),
logins: 3,
};
let (name, email) = user.into_contact();
println!("{name} <{email}>");
}The .. pattern ignores logins. Because logins is Copy, ignoring it costs nothing. Any ignored field that is not Copy is dropped when the method returns.
A decision guide
The diagram below summarizes how to choose.
Edge cases
Structs that implement Drop
If a struct implements Drop, you cannot move fields out of it, even from an owned value. The compiler reports error E0509. The reason is that drop receives &mut self and expects every field to still be valid. The usual workarounds are mem::take, mem::replace, or storing the movable field in an Option and calling take().
Struct update syntax moves fields
In Config { retries: 5, ..base }, every field taken from base that is not Copy is moved. After that, base is partially moved. The earlier example used ..base.clone() to avoid this. If only Copy fields come from the base, the base stays fully usable.
Closures and pattern matching
A match or let pattern that binds a non-Copy field by value also moves it. Matching on &self.field or using ref borrows instead. Since Rust 2021, closures capture individual fields rather than the whole struct, so a closure that moves user.name leaves user.email usable.
Summary of rules
- A struct owns its non-reference fields, and dropping the struct drops them.
- Moving a non-
Copyfield out of an owned local value is a partial move, and the other fields stay usable. - Moving a field out through
&selfor&mut selfis an error. - Types that implement
Dropforbid moving fields out at all.
Exercise
A struct Session has the fields token: String and expires: u64. You want a method revoke(&mut self) -> String that returns the token and leaves the session with an empty token. Write the body, and explain why self.token alone does not compile.
Show answer
Use std::mem::take(&mut self.token). The body is fn revoke(&mut self) -> String { std::mem::take(&mut self.token) }. Writing self.token tries to move a String out from behind a &mut reference. That would leave the field without a valid value, so the compiler rejects it with E0507. mem::take swaps in String::default(), an empty string, so the struct remains valid.
Exercise
Given let u = User { name: String::from("Ada"), email: String::from("[email protected]"), logins: 1 }; and the statement let n = u.name;, which of these still compile: println!("{}", u.email);, println!("{}", u.logins);, println!("{}", u.name);, and passing u to a function that takes User?
Show answer
u.email and u.logins still compile, because only the name field was moved. u.name fails because it was moved out. Passing u as a whole also fails, because u is partially moved and cannot be used as a complete value.