error[E0505]: cannot move out of value because it is borrowed
You tried to move a value while a reference to it was still going to be used. The move would let the new owner free the value, and the reference would point at nothing.
Quick fix: Finish using the reference before the move, or copy (or clone) the data you need instead of borrowing it.
Code that triggers E0505
fn consume(scores: Vec<u32>) {
println!("{} scores", scores.len());
}
fn main() {
let scores = vec![90, 72, 85];
let first = &scores[0];
consume(scores);
println!("first score: {first}");
}What the compiler says
error[E0505]: cannot move out of `scores` because it is borrowed
--> src/main.rs:8:13
|
6 | let scores = vec![90, 72, 85];
| ------ binding `scores` declared here
7 | let first = &scores[0];
| ------ borrow of `scores` occurs here
8 | consume(scores);
| ^^^^^^ move out of `scores` occurs here
9 | println!("first score: {first}");
| ------- borrow later used here
|
help: consider cloning the value if the performance cost is acceptable
|
7 | let first = &scores.clone()[0];
| ++++++++
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0505`.Why Rust raises E0505
first is a reference into scores, and you use it on line 9. While that borrow is alive, Rust won’t let scores move into consume. Once consume owns the vector it frees it when it returns, and first would point at freed memory.
A borrow is alive from where it’s created until its last use, not until the end of the block. That’s why the compiler marks three places: where the borrow starts (line 7), where you try to move (line 8), and where the borrow is used later (line 9). Remove the overlap and the error goes away.
How to fix E0505
1. Use the reference before the move
Move the last use of first above the call. The borrow ends on line 8, so moving scores on line 9 is allowed.
fn consume(scores: Vec<u32>) {
println!("{} scores", scores.len());
}
fn main() {
let scores = vec![90, 72, 85];
let first = &scores[0];
println!("first score: {first}");
consume(scores);
}2. Copy the value instead of borrowing it
u32 is a Copy type, so let first = scores[0]; copies the number out. Nothing borrows scores any more, and the move is fine. For elements that aren’t Copy, such as String, clone the element instead.
fn consume(scores: Vec<u32>) {
println!("{} scores", scores.len());
}
fn main() {
let scores = vec![90, 72, 85];
let first = scores[0];
consume(scores);
println!("first score: {first}");
}Related errors
- E0382: borrow of moved value
- E0502: cannot borrow as mutable because it is also borrowed as immutable
- E0597: borrowed value does not live long enough
Learn the concept behind it
The References and Borrowing lesson explains the rules behind E0505 with diagrams and more examples. For the official reference, run rustc --explain E0505 or read the E0505 entry in the Rust error index .
Hit a different error? Paste it into the Rust error lookup to find its fix.