Value does not live long enough (lifetime error)
Quick Answer
Extend the lifetime of the value by moving it to a wider scope, return an owned value instead of a reference, or annotate lifetimes explicitly.
A reference outlives the value it points to. This is a core lifetime error — the borrowed value is dropped while a reference to it is still in scope or stored somewhere that expects a longer lifetime.
- 1Storing a reference to a local variable in a struct that outlives the function
- 2Returning a reference to a local variable from a function
- 3Holding a reference to a temporary created inside a block
Fix 1
Return owned value instead of reference
// Bad — returning reference to local
fn bad() -> &str {
let s = String::from("hello");
&s // error[E0597]: s does not live long enough
}
// Good — return owned String
fn good() -> String {
String::from("hello")
}Why this works
Returning an owned String transfers ownership to the caller, eliminating the need for a lifetime annotation.
Fix 2
Extend the scope of the value
// Move the value to a scope that outlives the reference
let owned = String::from("hello"); // lives in the outer scope
let reference: &str = &owned; // reference valid as long as owned lives
process(reference);Why this works
Declaring the owned value in the same or wider scope as the reference ensures the value lives at least as long as any borrow of it.
let r;
{
let x = 5;
r = &x; // error[E0597]: x does not live long enough
}
println!("{}", r);// rustc --explain E0597 // Gives the full explanation with lifetime annotation examples
Rust Compiler Error Index
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev