Sub topic 11
Owned fields and moves out of structs
This chapter assumes you know Rust's move and borrow rules, and how to define a struct and write impl blocks with self, &self, and &mut self.
A struct owns its fields
A field of type String or Vec<T> is owned by the struct. When the struct is dropped, its fields are dropped too. Moving the struct moves everything inside it.
You can also move a single field out of a struct you own. This is a partial move.
#[derive(Debug)]
struct User {
name: String,
email: String,
age: u32,
}
fn main() {
let user = User {
name: String::from("Ada"),
email: String::from("[email protected]"),
age: 36,
};
let name = user.name; // partial move: only `name` leaves the struct
println!("{name}");
println!("{}", user.email); // still valid
println!("{}", user.age); // still valid
// println!("{:?}", user); // error: borrow of partially moved value
}After the move, user.name is unusable, so the compiler rejects any use of user as a whole, such as {:?} or passing it to a function. The remaining fields can still be used individually. u32 is Copy, so reading user.age never moves anything.
You cannot move out of a borrow
A method that takes &self only borrows the struct, so it cannot take a field away from it.
impl User {
fn name(&self) -> String {
self.name // error[E0507]: cannot move out of `self.name`
// which is behind a shared reference
}
}There are three common fixes. Each one changes who ends up owning the data.
| Goal | Receiver | Technique |
|---|---|---|
| Look at the field | `&self` | Return a reference such as `&str` |
| Get an independent copy | `&self` | Call `.clone()` |
| Hand the field over | `self` | Move it out and consume the struct |
| Take it but keep the struct | `&mut self` | Replace it with `std::mem::take` |
use std::mem;
struct User {
name: String,
email: String,
}
impl User {
fn name(&self) -> &str {
&self.name
}
fn into_name(self) -> String {
self.name
}
fn take_email(&mut self) -> String {
mem::take(&mut self.email) // leaves String::new() behind
}
}
fn main() {
let mut user = User {
name: String::from("Ada"),
email: String::from("[email protected]"),
};
println!("{}", user.name());
let email = user.take_email();
println!("{email} / left behind: {:?}", user.email);
let name = user.into_name(); // `user` is consumed here
println!("{name}");
}mem::take requires the field type to implement Default. For a field of type Option<T>, self.field.take() does the same job and leaves None. If you have no sensible default, mem::replace lets you choose the value left behind.
Limits of partial moves
- A struct that implements
Dropcannot be partially moved. The compiler gives error E0509, becausedropneeds the whole value intact. - Partial moves only work on a binding you own. Moving a field out of
&mut Userfails the same way as with&User. - Moving a field in a method with
selfis fine, but the rest ofselfis dropped when the method ends.
Exercise
Why does fn email(&self) -> String { self.email } fail to compile, and what is one way to fix it without consuming the struct?
Show answer
It tries to move a String out of a shared borrow, which would leave the struct with an invalid field (error E0507). Return &str with &self.email, or return self.email.clone() if the caller needs an owned String.