Rust — cannot return reference to local temporary value
Fix return-of-local-reference errors by returning owned data or by borrowing a longer-lived source.
Symptoms
- error[E0515]: cannot return reference to local variable
- a reference to a temporary would be returned
- The function builds a value and tries to return a reference to it
- A closure returns a reference to a captured local
Possible causes
- A function returns a reference to a value it created locally
- A reference to a temporary expression escapes
- A closure tries to return a borrow of a local it captured by value
- A helper returns a reference into a dropped container
Diagnosis steps
Read which local is borrowed
cargo build 2>&1 | head -30Interpretation
The compiler names the local whose reference would escape, showing the lifetime mismatch.
Return an owned value
fn make() -> String { String::from("x") }Interpretation
Returning the owned value moves it out, so no reference to a local is needed.
Borrow from an input instead
fn pick<'a>(x: &'a str) -> &'a strInterpretation
Returning a reference derived from an input ties the output to data the caller owns.
Root cause
The function would return a reference to a value that is dropped when the function returns, so the reference would be dangling, and the compiler rejects it.
Fix
Return an owned value, or return a reference derived from an input whose lifetime outlives the call so the borrow remains valid for the caller.
Verify the fix
Rebuild and confirm the error is gone, then run tests confirming the returned data is usable and correct after the call returns.
Symptom walkthrough
The compiler refuses to return a reference to a local value, explaining that the reference would outlive the data. This happens when a function creates a value and tries to return a borrow of it, or when a closure returns a reference to a local it captured. The data is dropped at function exit, so any returned reference would dangle, which the checker prevents.
Fix in practice
Return the owned value and let the caller decide how to store it, or derive the returned reference from an input parameter whose lifetime outlives the call. Either makes the ownership explicit and removes the dangling reference.
Verification
Rebuild and confirm the error is gone, then run tests that use the returned data after the call returns. Successful use confirms the returned value or borrow is valid.
Diagnostic commands
Check the behavior with commands like these:
cargo build 2>&1 | head -30
fn make() -> String { String::from("x") }
fn pick<'a>(x: &'a str) -> &'a str