Rust E0716: temporary value dropped while borrowed
E0716 means a reference outlived the temporary that owned its data. Bind the temporary to a variable, restructure the expression, or take ownership.

Introduction & Quick Summary
The borrow checker rejects a reference to a value that never got a name:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:4:28
|
4 | let label = &format!("item-{}", id).as_str()[..];
| ^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary value which is
| freed at the end of this statement
|
= note: consider using a `let` binding to create a longer lived valueformat! returns an owned String. Calling .as_str() borrows from it, and the String itself is a temporary with a lifetime that ends at the semicolon. The reference outlives its owner by one statement, so the compiler refuses.
The compiler's suggestion is usually correct: bind the owner first, then borrow.
let owned = format!("item-{}", id);
let label = &owned[..];Three shapes account for most E0716 cases:
- A method chain that returns a reference into an unnamed temporary.
- A
matchorif letscrutinee whose temporary is dropped before the body ends. - A tail expression where the temporary is created inside a block and the reference escapes it.
The fix is always about ownership: either give the temporary a name that lives long enough, or take ownership and stop borrowing.
Core Mechanics, Signatures & Reproducible Setup
Rust drops temporaries at the end of the enclosing statement, not at the end of the block. A let binding extends the life of the initializer to the block, which is why the two-line version compiles and the one-line version does not.
fn main() {
let id = 7;
let bad = &format!("item-{id}").as_str()[..]; // E0716
let owned = format!("item-{id}");
let good = &owned[..]; // ok: owned lives in the block
println!("{good}");
}Reproduce with rustc --edition 2021 src/main.rs, or in a project with cargo build. The error includes the exact lifetime span, which is more useful than the message: it shows where the temporary is created and where the borrow would need to live.
The neighbourhood of messages distinguishes three different problems:
| Error | Meaning |
|---|---|
| E0716 | reference outlives the temporary that owns the data |
| E0597 | borrowed value does not live long enough (named binding) |
| E0515 | cannot return reference to a local variable |
| E0505 | cannot move out of a value while borrowed |
| E0382 | use of moved value, often after a clone was missed |
Key Comparison Table
| Fix | Allocation | Readability | Use when |
|---|---|---|---|
let binding for the owner | same as before | high | default, wherever possible |
Return owned String or Vec | one allocation | high | value escapes the function |
Cow<'_, str> | conditional | medium | sometimes borrowed, sometimes owned |
clone() at the boundary | extra allocation | high | small values in hot paths only if measured |
| Restructure to one expression | none | varies | temporary was unnecessary |
Box::leak | leaks memory | low | never in normal code |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. .as_str() on a temporary String
This is the canonical form of the error. The chain reads naturally and hides the fact that an owner is created in the middle.
fn describe(id: u32) -> &str {
&format!("item-{id}") // E0515 here, E0716 at the call site
}
fn describe_owned(id: u32) -> String {
format!("item-{id}") // owns the value, no borrow to outlive
}Returning String is the fix, not a compromise. The function produces new text; only a caller that already holds storage should receive a borrowed slice.
2. Method chains that return references
Builder APIs and getters often return &T from a value produced in the same expression. Assigning the reference to a variable keeps only the reference, not the value.
struct Config { name: String }
impl Config {
fn new(name: &str) -> Self { Config { name: name.to_string() } }
fn name(&self) -> &str { &self.name }
}
fn main() {
let n = Config::new("prod").name(); // E0716
let cfg = Config::new("prod");
let n = cfg.name(); // ok
println!("{n}");
}The two-line version is not a workaround; it states the ownership that the value already had.
3. match and if let on a temporary
The scrutinee temporary lives for the whole match in most cases, but a reference extracted from it can still escape the arm.
fn main() {
let data = vec![1, 2, 3];
let first = match data.iter().max() {
Some(v) => v, // ok: data outlives the match
None => return,
};
let bad = match vec![1, 2, 3].iter().max() {
Some(v) => v, // E0716: the Vec dies with the match
None => return,
};
}Binding the Vec before the match is the fix. When the value is only needed inside the arm, compute it there and return an owned result instead of a reference.
4. Tail expressions and block scope
A block's tail expression is the block's value, and temporaries created there die before the outer binding uses the reference.
fn main() {
let s = {
let tmp = String::from("hello");
&tmp[..] // E0597: tmp does not live long enough
};
let s = {
let tmp = String::from("hello");
tmp // move the owner out
};
}Moving the owner out of the block is the only correct option. A reference cannot escape the scope that owns its data, and no annotation changes that.
5. Iterators over temporaries
for x in vec![1, 2, 3].into_iter() consumes the temporary, which is fine because the loop body owns the items. Collecting references from a temporary is where the error appears.
let names: Vec<&str> = vec![String::from("a"), String::from("b")]
.iter()
.map(|s| s.as_str())
.collect(); // E0716: the Vec is dropped at the semicolon
let source = vec![String::from("a"), String::from("b")];
let names: Vec<&str> = source.iter().map(|s| s.as_str()).collect();For the one-expression case, collect owned Strings instead: .map(|s| s.clone()) is honest when the source is temporary.
6. Lock guards and interior mutability
A MutexGuard is a temporary in an expression. Taking a reference into the guarded data and letting the guard drop leaves a dangling reference.
use std::sync::Mutex;
static STATE: Mutex<Vec<String>> = Mutex::new(Vec::new());
fn first() -> Option<String> {
let guard = STATE.lock().unwrap(); // guard must outlive the borrow
guard.first().cloned() // clone before the guard drops
}If a clone is too expensive, restructure so the caller holds the guard, or use an owned snapshot type. Returning a reference while the mutex unlocks would be a data race, which is exactly what the compiler prevents.
Common Compilation/Runtime Mistakes & Version Gotchas
clone()reflexively. It compiles and hides the ownership question. Clone at the boundary only when the value is small and the borrow cannot live long enough for a real reason.Box::leakto extend lifetimes. It turns a compile error into a permanent memory leak. Acceptable only for values that genuinely live for the process.- Assuming editions change the rule. Temporary scope rules are stable across editions; the 2024 edition narrowed some
if lettemporary lifetimes, which removes certain E0716 cases but does not change ownership. - Annotating lifetimes as a fix.
fn f<'a>(x: &'a str) -> &'a strcannot extend a temporary. Lifetimes describe relationships; they never create storage. - Ignoring the second span. The note points at the declaration of the temporary, which tells you exactly which value needs a name.
| Symptom | Cause | Fix |
|---|---|---|
| error on a one-liner, fine when split | statement-scoped temporary | bind the owner |
error inside a closure returning &str | closure returns a reference to a captured temporary | return owned data |
compiles with .to_string() | an allocation was added | keep it if the value escapes |
| error only in a trait impl | associated type borrow | tie the type to a parameter lifetime |
Use the text diff tool to compare a signature that compiles with one that does not, and the JSON formatter when a borrowed field comes from deserialized input, where the owned value is often the right return type.
The error index has a dedicated page for E0716 with the exact rules, and the ownership chapter covering references and borrowing explains why the lifetime cannot be extended after the fact.
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 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.
Rust E0106: missing lifetime specifier
E0106 appears when a returned borrow has no input to borrow from. Name the lifetime in functions, structs and impls, or return owned data.
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.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.