Answer#
Every value is freed when the block that owns it ends. A reference to it is only valid until then. E0597 says that a reference is still used after that moment, and the message marks three places: where the value is declared, where it is dropped, and where the reference is used later.
fn main() {
let longest: &str;
{
let text = String::from("a short-lived value");
longest = &text;
}
println!("{longest}");
}error[E0597]: `text` does not live long enough
--> src/main.rs:5:19
|
4 | let text = String::from("a short-lived value");
| ---- binding `text` declared here
5 | longest = &text;
| ^^^^^ borrowed value does not live long enough
6 | }
| - `text` dropped here while still borrowed
7 | println!("{longest}");
| ------- borrow later used here
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0597`.Here text lives inside the inner braces, but longest is read after them.
How to fix it#
Choose by what the code needs:
- Make the owner live as long as the reference: declare it in the outer scope.
fn main() {
let text = String::from("a value that lives long enough");
let longest: &str = &text;
println!("{longest}");
}a value that lives long enough- Keep an owned value instead of a reference:
let longest = text.clone();or build aStringin the first place. - In a function: do not return
&local. Return the owned value; the caller then becomes its owner.
Common mistakes#
- Adding lifetime annotations hoping to fix it. Annotations describe relationships, they cannot make a value live longer.
- Storing a reference to a loop variable in a collection that outlives the loop. Push owned copies instead.