error[E0597]: borrowed value does not live long enough
A reference outlives the value it points to. The value is dropped at the end of its scope while something still borrows it, which would leave a dangling reference.
Quick fix: Move the value to a scope that lives at least as long as the reference, or move (or clone) the value instead of borrowing it.
Code that triggers E0597
fn main() {
let winner;
{
let name = String::from("Ferris");
winner = &name;
}
println!("winner: {winner}");
}What the compiler says
error[E0597]: `name` does not live long enough
--> src/main.rs:5:18
|
4 | let name = String::from("Ferris");
| ---- binding `name` declared here
5 | winner = &name;
| ^^^^^ borrowed value does not live long enough
6 | }
| - `name` dropped here while still borrowed
7 | println!("winner: {winner}");
| -------- borrow later used here
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0597`.Why Rust raises E0597
name is created inside the inner block and dropped at its closing brace on line 6. winner belongs to the outer scope and is used on line 7, after name is gone. If this compiled, winner would point at freed memory.
The three markers in the output tell the whole story: where the borrow is taken (line 5), where the owner is dropped (line 6), and where the borrow is still used (line 7).
How to fix E0597
1. Make the owner live as long as the reference
Declare name in the outer scope so it lives at least as long as winner.
fn main() {
let name = String::from("Ferris");
let winner;
{
winner = &name;
}
println!("winner: {winner}");
}2. Move the value instead of borrowing it
If the value is only needed outside the block, move it out: winner = name; transfers ownership, so nothing dangles.
fn main() {
let winner;
{
let name = String::from("Ferris");
winner = name;
}
println!("winner: {winner}");
}Related errors
- E0106: missing lifetime specifier
- E0515: cannot return reference to local variable
- E0716: temporary value dropped while borrowed
Learn the concept behind it
The References and Borrowing lesson explains the rules behind E0597 with diagrams and more examples. For the official reference, run rustc --explain E0597 or read the E0597 entry in the Rust error index .
Hit a different error? Paste it into the Rust error lookup to find its fix.