Rust E0597: borrowed value does not live long enough
E0597 says a borrow outlives the value it points at. Reorder the declarations, own the data, or annotate a lifetime only when the holder truly borrows.

Introduction & Quick Summary
The borrow checker rejects code that never dereferences anything wrongly:
error[E0597]: `config` does not live long enough
--> src/main.rs:8:14
|
6 | let handle = store.insert(&config);
| ------- borrow occurs here
7 | }
| - `config` dropped here while still borrowedQuick answer: the reference outlives the value it points to. Either keep the value alive longer, or let the collector own a copy.
let config = Config::load()?;
let handle = store.insert(&config); // borrow ends before `config` drops
drop(handle); // or simply reorder so this is not neededE0597 is a lifetime of the borrow error, not a type error. The compiler proved that a borrow of some local is still live at a point where the local is dropped — usually at the end of the enclosing block, because Rust drops locals in reverse order of declaration. Fixing it means changing which value owns the data, or where the borrow ends, rather than adding annotations until the message disappears.
Core Mechanics, Signatures & Reproducible Setup
Reproduce the canonical version:
struct Store {
name: String,
}
fn main() {
let mut store: Vec<&str> = Vec::new();
{
let s = String::from("temporary");
store.push(&s); // E0597: `s` does not live long enough
}
println!("{:?}", store);
}store outlives the inner block, s does not, and pushing &s requires s to live at least as long as store. The fix is either to own the data (store.push(s) with Vec<String>) or to shorten the store's life.
The important subtlety: a borrow ends at its last use (non-lexical lifetimes), not at the end of the block. That is why moving a println! above the closing brace often fixes E0597 without any other change.
| Code | Message | What it means |
|---|---|---|
error[E0597] | x does not live long enough | borrowed value dropped while borrow live |
error[E0716] | temporary value dropped while borrowed | temporary created in an expression |
error[E0505] | cannot move out because it is borrowed | move while a borrow is live |
error[E0515] | cannot return reference to local | returning a borrow of a local |
error[E0106] | missing lifetime specifier | signature needs 'a |
Key Comparison Table
Five repairs, and when each is the honest one:
| Repair | Code change | Cost | Use when |
|---|---|---|---|
| Reorder or scope | end the borrow earlier | none | the borrow is only needed briefly |
| Own the data | Vec<String>, String parameter | allocation | the container outlives the source |
| Clone deliberately | value.clone() | allocation | data is small and shared briefly |
| Borrow with a lifetime | struct Holder<'a> { s: &'a str } | none, ties lifetimes | the holder truly cannot outlive the source |
| Share ownership | Arc<T> | atomic refcount | multiple owners, threads |
The lifetime-related errors that look like E0597 but are not:
| Situation | Code | Fix |
|---|---|---|
| returning a reference to a local | fn f() -> &str { let s = String::new(); &s } | return String |
temporary in a let | let x = &String::from("a").as_str(); | bind the owner first |
guard across await | let g = m.lock().unwrap(); then .await | scope the guard |
| iterator borrowing a local | .iter() collected into Vec<&T> | collect owned values |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Drop order is the whole story
Locals drop in reverse declaration order. Declaring the borrowed value before the borrower is what makes the borrow valid:
let config = Config::default();
let mut app = App::new(&config); // `app` drops first, then `config`
app.run();Reversing those two lines produces E0597 even though nothing else changed, because config would then drop while app still holds a reference. This single rule explains most E0597 reports in main functions and test bodies.
2. Functions that return borrows
// wrong: the returned reference would outlive its source
fn label(name: &str) -> &str {
let prefix = String::from("user:");
prefix.push_str(name);
&prefix // E0515, often surfaced as E0597 at the call site
}
// right: return owned data
fn label(name: &str) -> String {
format!("user:{name}")
}A function may return a borrow only from one of its parameters, and the signature must say which:
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}The 'a here is not a new lifetime; it is a promise that the output lives no longer than the shortest input. When a struct stores references, the same annotation is required on the struct (struct View<'a> { title: &'a str }), and every use of the struct inherits the constraint.
3. Cow: borrow when possible, own when necessary
use std::borrow::Cow;
fn normalize(input: &str) -> Cow<'_, str> {
if input.contains(' ') {
Cow::Owned(input.replace(' ', "_"))
} else {
Cow::Borrowed(input)
}
}Cow removes a whole category of E0597/E0515 errors in parsing code: the function can return the input unchanged without allocating, and allocate only when it must modify something. The same idea appears with Path::to_owned, OsStr::to_string_lossy and slice::to_vec.
4. Iterators and closures borrowing a local
let suffixes = vec!["-a", "-b"];
let names: Vec<String> = users
.iter()
.map(|u| format!("{}{}", u.name, suffixes[0]))
.collect();This compiles because suffixes outlives the iterator. The failing version usually looks like building a Vec<&String> inside a loop, where each iteration creates the borrowed value:
let mut refs = Vec::new();
for i in 0..3 {
let s = format!("item-{i}");
refs.push(&s); // E0597: s dropped at the end of each iteration
}The repair is refs.push(s) with Vec<String>, or collecting the produced strings directly with map(|i| format!("item-{i}")).collect::<Vec<_>>().
5. Async: guards and temporaries across await
// E0597 in async code, usually combined with "future cannot be sent"
async fn update(state: Arc<Mutex<State>>) {
let mut guard = state.lock().unwrap();
guard.count += 1;
some_async_call().await; // guard is still alive here
}Two fixes, both explicit:
async fn update(state: Arc<Mutex<State>>) {
{
let mut guard = state.lock().unwrap();
guard.count += 1;
} // borrow ends here
some_async_call().await;
}drop(guard) reads better than braces when the intent is "release the lock now". Holding a MutexGuard across await also makes the future non-Send, which the compiler reports separately, so fixing E0597 this way usually removes two errors at once.
6. When 'static is the wrong answer
'static means "valid for the whole program", and it silences the error only if the data genuinely deserves that lifetime: string literals, leaked boxes, values moved into a thread::spawn. Box::leak makes a value 'static by never freeing it, which is a memory leak dressed as a fix. If a value must outlive a scope, prefer Arc<T> or restructure the ownership so a single owner holds it and the rest borrow within a narrow scope. Comparing two versions of a file after such a refactor is quickest with the text diff tool, and serialized state that crosses the boundary is easier to inspect with the JSON formatter.
Common Compilation/Runtime Mistakes & Version Gotchas
Annotating instead of restructuring. Adding 'a to a function that returns a reference to a local cannot work; no annotation makes a local outlive its block.
Cloning at every call site. It compiles and allocates on every call. Cow, borrowing parameters and returning owned values usually remove more clones than they add.
Reading E0597 as a runtime bug. Nothing here can crash; a program with E0597 does not compile. A panic at runtime with a similar name is a different problem, usually an unwrap on None.
Fighting the borrow checker with unsafe. A raw pointer that outlives its allocation compiles and produces undefined behaviour. Do not use unsafe to escape E0597.
Version notes. Non-lexical lifetimes landed in Rust 2018 (compiler 1.31) and made borrows end at their last use, which fixed thousands of E0597 reports overnight. The 2021 edition changed closure capture to capture individual fields, which can shorten borrows and occasionally changes which error appears. The 2024 edition goes further on temporary lifetimes in if let and tail expressions, so code that compiled under 2021 can produce new E0716/E0597 errors after cargo fix --edition; read each one rather than adding clone() until the errors stop.
Reference material: E0597 and Validating references with lifetimes.
Official references
primary documentationThe Rust documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust E0061: this function takes 1 argument but 2 were supplied
E0061 counts arguments at the call site. Check the signature, method versus associated function, generic defaults, and trait impls that changed arity.
Rust E0282: type annotations needed
E0282 means inference ran out of information. Annotate the binding, add a turbofish to collect or parse, or fix the signature the value flows into.
Rust E0463: can't find crate for std
The target triple has no standard library installed. Add the target with rustup, check the target string and link the right ABI.
Rust E0432: unresolved import
E0432 is a module graph problem: a missing mod declaration, a private parent or a wrong path. Fix the tree, not the dependency list.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.