Sub topic 4
Moves: transferring ownership
What this chapter assumes
You know basic Rust syntax, can run a program with cargo, and have seen the three ownership rules: every value has one owner, there is only one owner at a time, and the value is dropped when the owner goes out of scope. This chapter covers what happens when ownership changes hands. Rust calls that a move.
What a move is
A move transfers ownership of a value from one variable to another. After the move, the old variable is no longer valid. The compiler rejects any later use of it.
fn main() {
let s1 = String::from("hello");
let s2 = s1;
// println!("{s1}"); // error: borrow of moved value: `s1`
println!("{s2}");
}The commented-out line fails with borrow of moved value: s1. If you remove the comment markers, the compiler points at the line that moved the value and at the line that tried to use it.
What happens in memory
A String is a small struct on the stack with three fields: a pointer to heap bytes, a length, and a capacity. The text itself lives on the heap.
let s2 = s1; copies those three stack fields into s2. It does not copy the heap bytes. Right after the assignment, both variables would point at the same heap buffer.
If both stayed valid, both would be dropped at the end of scope. The buffer would be freed twice, which is a double free. Rust prevents this by marking s1 as moved-from. Only s2 is dropped, so the buffer is freed exactly once.
A move is cheap. It copies a fixed number of bytes no matter how large the heap data is. Nothing is allocated, and nothing is freed.
Moves happen in more places than assignment
Any place that gives a value to a new owner is a move. The common cases are:
- Assigning to another variable with
let b = a;. - Passing a value as a function argument.
- Returning a value from a function.
- Pushing a value into a collection such as a
Vec. - Capturing a value in a
moveclosure. - Binding a field out of a struct or enum by pattern matching.
The same rule applies to all of them. The source stops being usable unless its type is Copy, which the next chapter covers.
Moves and drop
A move changes who runs Drop. It does not run Drop at the moment of the move. The moved-from variable is not dropped at the end of its scope, because it no longer owns anything.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn consume(n: Noisy) {
println!("consuming {}", n.0);
}
fn main() {
let a = Noisy("a");
let b = Noisy("b");
consume(a);
println!("back in main");
let _keep = b;
}This prints:
consuming a
dropping a
back in main
dropping ba is dropped when consume ends, because that function owns it by then. b is moved into _keep and dropped when main ends. Each value is dropped exactly once.
Conditional and partial moves
The compiler tracks moves along every code path. A value moved in only one branch counts as possibly moved afterward.
fn main() {
let name = String::from("Ferris");
let flag = std::env::args().count() > 5;
if flag {
drop(name);
}
// println!("{name}"); // error: borrow of possibly-moved value
println!("done");
}The compiler does not know at compile time whether flag is true, so it assumes the worst. It reports that name may have been moved.
You can also move one field out of a struct. This is a partial move.
struct User {
name: String,
email: String,
}
fn main() {
let user = User {
name: String::from("Ana"),
email: String::from("[email protected]"),
};
let name = user.name;
println!("{name}");
println!("{}", user.email);
// println!("{}", user.name); // error: moved
// let u2 = user; // error: partially moved
}After a partial move, the remaining fields can still be used on their own, but the struct as a whole cannot be used. A partial move is only allowed if the struct does not implement Drop. Otherwise the destructor would see a half-empty value.
Moves out of borrowed data and collections
You cannot move out of something you only borrow. Indexing a Vec is a common trigger.
fn main() {
let v = vec![String::from("a"), String::from("b")];
// let first = v[0]; // error: cannot move out of index of `Vec<String>`
let first = &v[0];
println!("{first}");
}A move would leave a hole in the vector, and the vector would later drop that slot again. Rust refuses. You have three choices:
- Borrow the element with
&v[0]. - Copy it with
v[0].clone(). - Take it out with an operation that handles the gap, such as
v.remove(0),v.swap_remove(0), orstd::mem::take(&mut v[0]).
std::mem::take replaces the slot with the type's default value and returns the old value. std::mem::replace does the same with a value you choose.
Moves in loops
A move inside a loop body is an error if the loop could run again with the same variable.
fn consume(s: String) {
println!("{s}");
}
fn main() {
let s = String::from("x");
for _ in 0..2 {
// consume(s); // error: value moved in previous iteration of loop
}
consume(s);
}Fixes include cloning inside the loop, passing a reference, or restructuring so the value is moved only once. A for loop over a Vec also moves it:
fn main() {
let names = vec![String::from("a"), String::from("b")];
for n in names {
println!("{n}");
}
// println!("{}", names.len()); // error: `names` moved into the loop
}Use for n in &names to borrow instead.
Reassigning a moved variable
A moved-from variable declared with mut can be given a new value. It becomes valid again.
fn main() {
let mut s = String::from("first");
let t = s;
s = String::from("second");
println!("{s} {t}");
}The assignment to s does not drop anything, because the old value was already moved out.
Common errors
| Error message | Typical cause | Usual fix |
|---|---|---|
| `borrow of moved value` | Used a variable after passing it by value | Borrow with `&`, or clone before the move |
| `use of moved value` | Moved twice, for example in a loop | Move once, or clone |
| `cannot move out of index` | Moved an element out of a `Vec` or array | Borrow, clone, or use `remove`/`take` |
| `cannot move out of borrowed content` | Moved a field through a `&` reference | Clone the field, or borrow it |
| `value partially moved` | Moved one field, then used the whole struct | Use the other fields individually, or clone |
Exercises
Exercise
Why does let s2 = s1; with s1: String make s1 unusable, even though only three words on the stack are copied?
Show answer
The copied pointer in s2 and the one in s1 would point to the same heap buffer. If both were dropped, the buffer would be freed twice. Rust marks s1 as moved-from so that only s2 is dropped.
Exercise
This code does not compile. Name the error and give two ways to fix it. fn main() { let words = vec![String::from("a"), String::from("b")]; let first = words[0]; println!("{first}"); }
Show answer
The error is "cannot move out of index of Vec<String>". Fix it by borrowing (let first = &words[0];) or by cloning (let first = words[0].clone();). Using words.remove(0) also works if you want to take the element out of the vector.
Exercise
In the Noisy example, what is printed if consume(a); is removed and the program ends normally?
Show answer
The output is "back in main", then "dropping b" and "dropping a" is not in that order. Locals drop in reverse declaration order, so _keep (holding b) is dropped first, then a. The output is "back in main", "dropping b", "dropping a".