Sub topic 7
Fixing Use of Moved Values
This chapter assumes you can read a basic rustc diagnostic (error code, message, labels, notes, help) and that you have met ownership and references once. You will learn why E0382 happens, how to read its labels, and how to choose between borrowing, cloning, and restructuring.
Why a value moves
Every value in Rust has one owner. When you assign a value of a non-Copy type to another binding, pass it to a function by value, or return it, ownership moves. The old binding is no longer valid, and the compiler rejects any later use.
Types like i32, bool, char, and &T implement the Copy trait, so assignment duplicates the bits and both bindings stay valid. Types that own heap data, such as String, Vec<T>, and Box<T>, do not implement Copy. They move.
fn main() {
let name = String::from("Ferris");
let greeting = name;
println!("{name} {greeting}");
}
// Fix: clone when both bindings need to own the data.
// let greeting = name.clone();Running cargo check reports E0382, "borrow of moved value: name". Moves are checked at compile time, so there is no runtime cost and no dangling pointer.
Reading an E0382 diagnostic
The diagnostic for the program above has these parts:
- The message names the moved binding: `
borrow of moved value:name`. If the later use was a move rather than a borrow, it says "use of moved value". - One label marks where the value was declared and tells you its type, for example "move occurs because
namehas typeString, which does not implement theCopytrait". - A second label marks the move itself, such as
let greeting = name;with "value moved here". - A third label marks the later use, "value borrowed here after move". The
println!macro borrows its arguments, which is why the message says borrow. - A
helpoften suggests.clone(), with the cloned expression shown.
Read the labels in source order: declaration, move, use. The fix always lives at one of these three places. Either the move should not happen (borrow instead), the value should be duplicated at the move (clone), or the later use should go away or change.
Choosing a fix
There are four common strategies. The right one depends on who needs to own the data afterwards.
| Situation | Fix | Cost |
|---|---|---|
| The callee only reads the value | Pass `&value` and take `&T` | None |
| The callee must modify it, and you want the changes | Pass `&mut value` and take `&mut T` | None |
| Both sides need independent owned copies | `.clone()` | Allocation and copy |
| The callee should take ownership and give it back | Return the value from the function | None, but clumsy API |
Other options exist for shared ownership, such as Rc<T> or Arc<T>, which this chapter only mentions. Reach for them when several owners must exist at once and the lifetime of the data is not tied to one scope.
Fix 1: borrow instead of move
The most common move error is passing a value to a function that only needs to look at it.
fn print_length(s: String) {
println!("{} has {} bytes", s, s.len());
}
fn main() {
let title = String::from("Rust");
print_length(title);
println!("Done with {title}");
}The call print_length(title) moves title into the parameter s. When print_length returns, s is dropped, and title is gone. The println! that follows triggers E0382. The note in the diagnostic points at the function signature and says "consider changing this parameter type in function print_length to borrow instead if owning the value isn't necessary".
Follow that advice. Change the parameter to &str and pass a reference.
fn print_length(s: &str) {
println!("{} has {} bytes", s, s.len());
}
fn main() {
let title = String::from("Rust");
print_length(&title);
println!("Done with {title}");
}Using &str instead of &String is the idiomatic choice. A &String coerces to &str automatically, and &str also accepts string literals.
Fix 2: clone when both sides need ownership
Sometimes the callee really must own the value, for example because it stores it in a struct.
struct User {
name: String,
}
fn main() {
let name = String::from("Ada");
let first = User { name: name.clone() };
let second = User { name };
println!("{} and {}", first.name, second.name);
}The first User receives a copy. The second receives the original, so the last use of name is the move. Order matters here. If you wrote User { name } first, the later name.clone() would fail with E0382.
Clone only as many times as you need. A common beginner pattern is to add .clone() everywhere until the errors stop. That compiles, but it hides the design question of who owns the data. If you see cloning inside a hot loop, revisit the design.
Moves inside loops
A move in a loop body is an error because the second iteration would use a value that the first iteration already moved.
fn consume(s: String) {
println!("{s}");
}
fn main() {
let message = String::from("hello");
for _ in 0..2 {
consume(message);
}
}rustc reports E0382 with the label "value moved here, in previous iteration of loop". Choose a fix based on intent.
- If
consumeonly reads, change it to take&strand pass&message. - If each iteration needs its own copy, pass
message.clone(). - If the value should be consumed exactly once, move the call out of the loop.
Partial moves out of structs
You can move a single field out of a struct. The struct is then partially moved, and you can no longer use it as a whole, though other fields stay usable.
struct Person {
name: String,
age: u32,
}
fn main() {
let p = Person { name: String::from("Grace"), age: 30 };
let n = p.name;
println!("{} {}", n, p.age);
}This compiles, because p.age is a u32 and was never moved. If you added println!("{}", p.name) you would get E0382, and passing p whole to a function would get "borrow of partially moved value". The fix is the same as before: borrow the field with &p.name or clone it.
Moves through method calls
Methods whose first parameter is self take ownership. Many standard library methods do this, including into_iter, into_bytes, unwrap, and into_boxed_str.
fn main() {
let words = vec![String::from("a"), String::from("b")];
for w in words {
println!("{w}");
}
println!("{}", words.len());
}The for loop calls IntoIterator::into_iter(words), which consumes the vector. The note in the diagnostic says so: "words moved due to this implicit call to .into_iter()". The fix is to iterate by reference.
fn main() {
let words = vec![String::from("a"), String::from("b")];
for w in &words {
println!("{w}");
}
println!("{}", words.len());
}The same applies to Option<String>. Calling opt.unwrap() consumes opt. Use opt.as_ref() to get an Option<&String> without moving, or opt.as_deref() to get an Option<&str>.
Closures and `move`
A closure that uses a captured variable by value moves it into the closure. The move keyword forces this for all captures, which threads require.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("{:?}", data);
});
handle.join().unwrap();
// println!("{:?}", data); // E0382: data moved into the closure
}If the main thread needs data afterward, clone it before the closure and move the clone in, or share it with Arc.
Restructuring as a fix
When the same value must flow through several steps, consider these designs before cloning:
- Let functions take references and return new values, so the caller keeps ownership.
- Reorder statements so the move is the last use.
- Shorten the lifetime of a binding by limiting its scope with a block.
- Return ownership from a function that must consume the value, as in
fn add_suffix(mut s: String) -> String.
fn add_suffix(mut s: String) -> String {
s.push_str("!");
s
}
fn main() {
let word = String::from("hi");
let word = add_suffix(word);
println!("{word}");
}The second let word shadows the moved binding, so the name is valid again. Shadowing is a clean way to express "consume the old value and continue with the new one".
Workflow for any E0382
- Run
cargo checkand read the first E0382. - Find the "value moved here" label and the type note.
- Ask whether the receiver needs ownership. If not, change the signature or call to borrow.
- If ownership is needed and you still use the value, clone or reorder.
- Re-run
cargo check. A borrow fix can expose a new E0502 or E0499, which the next chapter covers.
Summary of edge cases
Copytypes never produce E0382. If the compiler says a type does not implementCopy, you cannot just add the trait unless every field isCopytoo, and then you derive it with#[derive(Clone, Copy)].- References are
Copy, so passing a&Ttwice is fine. A&mut Tis notCopy, but the compiler reborrows it automatically in most calls. - A move in one branch of an
ifmakes the value unusable after theifunless every other path reinitializes it. - Assigning a new value to a moved
mutbinding makes it valid again.
Exercise
The code below fails with E0382. Give two different fixes and say when you would pick each. fn shout(s: String) -> usize { println!("{}!", s.to_uppercase()); s.len() } fn main() { let word = String::from("hey"); let n = shout(word); println!("{word} has {n} bytes"); }
Show answer
Fix 1: change the signature to fn shout(s: &str) -> usize and call shout(&word). Pick this when the function only reads, which is the case here. It costs nothing and keeps word valid. Fix 2: call shout(word.clone()). Pick this only when the function must own its argument, for example to store it. It allocates a copy. A third option is to return the string from shout alongside the length, but that makes the API awkward.
Exercise
Why does for w in words { ... } followed by words.len() fail, and what is the smallest change that fixes it?
Show answer
The for loop calls into_iter on words, which takes the vector by value and moves it into the loop. After the loop, words is gone. Iterate over a reference instead with for w in &words, which borrows the vector and leaves it usable.