Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0597: does not live long enough
What it meansA reference outlives the value it points to. The value is dropped at the end of its scope while something still holds a borrow of it.
What rustc prints
error[E0597]: `y` does not live long enough
--> main.rs:10:16
|
9 | let y = 0;
| - binding `y` declared here
10 | x.x = Some(&y); // error: `y` does not live long enough
| ^^ borrowed value does not live long enough
11 | }
| - `y` dropped here while still borrowed
12 | println!("{:?}", x.x);
| --- borrow later used hereReal output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
Why it happens
- Pushing
&localinto a Vec that lives longer than the local. - Returning or storing a reference to a variable created inside a loop or block.
- Spawning a thread or task that borrows a local (use
move, or scoped threads).
How to fix it
1. Store owned values
Keep the String, not a reference to it.
let mut names: Vec<String> = Vec::new();
for line in input.lines() {
names.push(line.to_string());
}2. Move the value to the outer scope
Declare it where it lives as long as its borrowers.
let s = String::from("x");
let r;
r = &s;
println!("{r}");3. Use scoped threads
std::thread::scope lets threads borrow locals safely.
std::thread::scope(|sc| {
sc.spawn(|| println!("{}", data.len()));
});Other wordings of this error
does not live long enough, borrowed value does not live long enough, dropped here while still borrowed
The compiler team's explanation
This error occurs because a value was dropped while it was still borrowed.
Erroneous code example:
struct Foo<'a> {
x: Option<&'a u32>,
}
let mut x = Foo { x: None };
{
let y = 0;
x.x = Some(&y); // error: `y` does not live long enough
}
println!("{:?}", x.x);
Here, y is dropped at the end of the inner scope, but it is borrowed by x until the println. To fix the previous example, just remove the scope so that y isn't dropped until after the println
struct Foo<'a> {
x: Option<&'a u32>,
}
let mut x = Foo { x: None };
let y = 0;
x.x = Some(&y);
println!("{:?}", x.x);From rustc --explain E0597 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0382borrow of moved value
- E0499cannot borrow as mutable more than once at a time
- E0502cannot borrow as mutable because it is also borrowed as immutable
- E0106missing lifetime specifier
- E0594cannot assign to `ss.earth`, as `ss` is not declared as mutable
- E0596cannot borrow as mutable, as it is not declared as mutable
- E0621explicit lifetime required in the type of `y`
- E0623lifetime mismatch
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?