Sub topic 1
Moves: What Happens When You Assign a Value
In Rust, let b = a; does one of two things, depending on the type of a. It either leaves both variables usable, or it hands the value to b and makes a unusable. The second case is called a move. This chapter explains how moves work, where they happen, and which compiler errors they cause. The rest of the tutorial builds on this, because Copy and Clone exist to change or work around the move rule.
Prerequisites
This chapter assumes you already know:
- Basic Rust syntax: structs, enums, functions, and traits.
- The basics of ownership and borrowing: each value has one owner, and
&creates a reference. - How to run
cargo buildorcargo runand read a compiler error message.
You do not need to know Copy or Clone yet. Both are introduced in the next chapters.
Two assignments, two outcomes
Here are two assignments that look the same but behave differently.
fn main() {
let a = 5;
let b = a;
println!("{a} {b}");
let s = String::from("hi");
let t = s;
// println!("{s}"); // error: borrow of moved value: `s`
println!("{t}");
}After let b = a;, both a and b hold the integer 5. After let t = s;, only t is valid. The compiler rejects any later use of s, because the String value now belongs to t.
The rule is that assignment moves the value by default. A type can opt out of the move by implementing Copy. i32 does this, and String does not.
What a move does at runtime
A String is a small struct stored on the stack. It holds three words: a pointer to a heap buffer, a length, and a capacity. The text itself lives in the heap buffer.
When you write let t = s;, the compiler copies those three words into t. It does not copy the heap buffer. After that, s and t would both point to the same buffer. If both were still usable, both would free the buffer when they went out of scope, and that is a double free.
Rust avoids this by treating s as uninitialized after the move. Only t is dropped at the end of the scope, so the buffer is freed once.
Three points follow from this:
- A move is cheap. It copies a fixed number of bytes, no matter how large the heap data is.
- The check happens at compile time. In most cases no runtime flag is involved. The compiler may add hidden "drop flags" when a move happens only on some paths, but your code does not see them.
- The moved-from variable is not destroyed early. Its name is simply off limits until it is assigned again.
Where moves happen
Assignment with let is only one place. A value moves whenever it is used by value:
- Passing it to a function:
consume(s). - Returning it from a function.
- Pushing it into a collection:
v.push(s). - Calling a method that takes
selfrather than&self. - Capturing it in a
moveclosure. - Binding it by value in a pattern, such as
let Some(x) = opt. - Using it as the iterable in a
forloop:for x in v.
A function call shows this clearly:
fn consume(s: String) -> usize {
s.len()
}
fn main() {
let s = String::from("hello");
let n = consume(s);
println!("{n}");
// println!("{s}"); // error: borrow of moved value: `s`
}The parameter s inside consume owns the string. It is dropped when consume returns, so the caller cannot use it afterward. If the caller wants to keep using the value, the function should take &String or &str instead.
Moves are the default, not a heap rule
Many people assume only heap-allocated types move. That is not the rule. Every type moves unless it implements Copy. This struct holds one f64 and still moves:
struct Meters(f64);
fn main() {
let a = Meters(1.0);
let b = a;
// println!("{}", a.0); // error: borrow of moved value: `a`
println!("{}", b.0);
}The bytes copied for Meters are the same as for an f64. The only difference is that the compiler stops you from using a. Whether the source stays usable is a property of the type, set by whether it implements Copy. It does not depend on how the type is stored. The next chapter covers how a type opts in.
Moves in loops and branches
The compiler tracks moves along every path through your code. If a value might have been moved, you cannot use it. A move inside a loop body therefore fails on the second iteration, because the value is already gone.
for x in v moves v into the loop. Iterating over &v borrows it and leaves the vector usable:
fn main() {
let names = vec![String::from("a"), String::from("b")];
for n in &names {
println!("{n}");
}
println!("{}", names.len());
for n in names {
println!("{n}");
}
// println!("{}", names.len()); // error: borrow of moved value: `names`
}The compiler also rejects a move that happens in only one branch of an if. A later use is still an error, because the value may have moved.
Reassigning a moved variable
A moved-from variable can be used again if you assign it a new value. The variable must be declared mut:
fn main() {
let mut s = String::from("first");
let t = s;
s = String::from("second");
println!("{s} {t}");
}The assignment s = ... is allowed because it does not read the old value. It gives the binding a fresh value, so the binding becomes Owned again, as the diagram shows.
Partial moves
A move can take a single field out of a struct. The remaining fields stay usable, but the struct as a whole does not:
struct User {
id: u32,
name: String,
email: String,
}
fn main() {
let u = User {
id: 1,
name: String::from("Ada"),
email: String::from("[email protected]"),
};
let name = u.name;
println!("{} {}", u.id, u.email);
println!("{name}");
// let whole = u; // error: use of partially moved value: `u`
}Here u.name is moved into name. The field u.id is an integer, and u.email was never moved, so both can still be read. Using u as a whole value is an error.
Partial moves have a limit. If the struct implements Drop, you cannot move a field out of it. The drop method would then run on a struct with a missing field, so the compiler reports error E0509.
Moving out of borrowed content
You can only move a value out of something you own. A reference does not own its target, so this is an error:
fn main() {
let v = vec![String::from("x"), String::from("y")];
// let first = v[0]; // error[E0507]: cannot move out of index of `Vec<String>`
println!("{}", v.len());
}Indexing gives you a place inside the vector. Moving out would leave a hole in the middle of the vector's buffer. You have several correct options, depending on what you need:
| Goal | Code | Effect |
|---|---|---|
| Read without taking | `let first = &v[0];` | Borrows the element. |
| Keep both copies | `let first = v[0].clone();` | Duplicates the element, which costs an allocation. |
| Take it and leave a default behind | `std::mem::take(&mut v[0])` | Replaces the slot with `String::new()`. |
| Remove it from the vector | `v.remove(0)` or `v.swap_remove(0)` | Shifts or swaps other elements. |
Here is mem::take in a complete program:
fn main() {
let mut v = vec![String::from("x"), String::from("y")];
let first = std::mem::take(&mut v[0]);
println!("{first:?} {v:?}");
}This prints "x" ["", "y"]. The vector keeps its length, and the slot holds an empty string.
Reading the error messages
Move errors are among the most common ones you will meet. Most have the code E0382. A typical message has three parts: where the value was moved, where you used it afterward, and a note saying the type does not implement Copy. For example:
value moved herepoints at the move.value borrowed here after movepoints at the later use.move occurs because ... does not implement the Copy traitnames the reason.
The first location tells you which operation consumed the value. That is usually where the fix goes.
| Error | Meaning | Usual fix |
|---|---|---|
| E0382 | Use of a moved or partially moved value | Borrow instead, clone, or restructure |
| E0382 (in a loop) | Value moved in a previous iteration | Borrow in the loop, or move after the loop |
| E0505 | Moved out while a borrow is still alive | End the borrow before the move |
| E0507 | Cannot move out of a reference or index | Clone, `mem::take`, or `remove` |
| E0509 | Cannot move out of a type that implements `Drop` | Clone the field or use `mem::take` |
Summary of the rules
- Using a value by value moves it, unless its type is
Copy. - A move copies the value's bytes shallowly and invalidates the source. Heap data is not copied.
- The compiler tracks moves along every code path, including loops and branches.
- A moved-from
mutbinding can be reassigned and used again. - Fields can be moved out of a struct individually, unless the struct implements
Drop. - You cannot move out of a reference or an indexed element.
Exercise
The program below does not compile. Which line causes the error, why, and give two different ways to fix it without changing show's signature.
fn show(s: String) {
println!("{s}");
}
fn main() {
let msg = String::from("hello");
show(msg);
println!("{}", msg.len());
}
Show answer
The call show(msg) moves msg into the function, so msg.len() on the next line uses a moved value (E0382). Fix 1: pass a clone, show(msg.clone());, so main keeps its own copy. Fix 2: reorder the code so the use comes first, let n = msg.len(); show(msg); println!("{n}");, so msg is not used after the move.
Exercise
Given struct Pair { a: String, b: String } and let p = Pair { a: String::from("x"), b: String::from("y") };, what happens after let first = p.a;? Can you still print p.b? Can you pass p to a function that takes a Pair? Would your answer change if Pair implemented Drop?
Show answer
After let first = p.a; the field p.a has been moved out, which is a partial move. You can still read p.b because it was not moved. You cannot pass p as a whole, because it is partially moved. If Pair implemented Drop, the line let first = p.a; would not compile at all (E0509), since the destructor would then run on a struct with a missing field.