Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readRust
#Rust#Borrow Checker#Lifetimes#Errors
A Rust value crate vanishing at the end of a cyan statement, an amber dangling reference beside it

Introduction & Quick Summary

The borrow checker rejects a reference to a value that never got a name:

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

format! 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.

rust
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 match or if let scrutinee 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.

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

ErrorMeaning
E0716reference outlives the temporary that owns the data
E0597borrowed value does not live long enough (named binding)
E0515cannot return reference to a local variable
E0505cannot move out of a value while borrowed
E0382use of moved value, often after a clone was missed

Key Comparison Table

FixAllocationReadabilityUse when
let binding for the ownersame as beforehighdefault, wherever possible
Return owned String or Vecone allocationhighvalue escapes the function
Cow<'_, str>conditionalmediumsometimes borrowed, sometimes owned
clone() at the boundaryextra allocationhighsmall values in hot paths only if measured
Restructure to one expressionnonevariestemporary was unnecessary
Box::leakleaks memorylownever 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.

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

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

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

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

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

rust
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::leak to 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 let temporary lifetimes, which removes certain E0716 cases but does not change ownership.
  • Annotating lifetimes as a fix. fn f<'a>(x: &'a str) -> &'a str cannot 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.
SymptomCauseFix
error on a one-liner, fine when splitstatement-scoped temporarybind the owner
error inside a closure returning &strclosure returns a reference to a captured temporaryreturn owned data
compiles with .to_string()an allocation was addedkeep it if the value escapes
error only in a trait implassociated type borrowtie 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 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.