Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readRust
#rust#e0597#lifetimes#borrow-checker
Bold white headline reading E0597 SHORT LIFETIME with a Rust reference crate floating above an amber dropped value block.

Introduction & Quick Summary

The borrow checker rejects code that never dereferences anything wrongly:

code
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 borrowed

Quick answer: the reference outlives the value it points to. Either keep the value alive longer, or let the collector own a copy.

rust
let config = Config::load()?; let handle = store.insert(&config); // borrow ends before `config` drops drop(handle); // or simply reorder so this is not needed

E0597 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:

rust
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.

CodeMessageWhat it means
error[E0597]x does not live long enoughborrowed value dropped while borrow live
error[E0716]temporary value dropped while borrowedtemporary created in an expression
error[E0505]cannot move out because it is borrowedmove while a borrow is live
error[E0515]cannot return reference to localreturning a borrow of a local
error[E0106]missing lifetime specifiersignature needs 'a

Key Comparison Table

Five repairs, and when each is the honest one:

RepairCode changeCostUse when
Reorder or scopeend the borrow earliernonethe borrow is only needed briefly
Own the dataVec<String>, String parameterallocationthe container outlives the source
Clone deliberatelyvalue.clone()allocationdata is small and shared briefly
Borrow with a lifetimestruct Holder<'a> { s: &'a str }none, ties lifetimesthe holder truly cannot outlive the source
Share ownershipArc<T>atomic refcountmultiple owners, threads

The lifetime-related errors that look like E0597 but are not:

SituationCodeFix
returning a reference to a localfn f() -> &str { let s = String::new(); &s }return String
temporary in a letlet x = &String::from("a").as_str();bind the owner first
guard across awaitlet g = m.lock().unwrap(); then .awaitscope 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:

rust
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

rust
// 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:

rust
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

rust
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

rust
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:

rust
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

rust
// 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:

rust
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 documentation

The Rust documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.