Skip to content
Latchkey

Rust "error[E0716]: temporary value dropped while borrowed" in CI

You took a reference to a temporary value, but that temporary is dropped at the end of the statement while the reference is still in use. The borrow would dangle, so the compiler rejects it.

What this error means

cargo build fails with error[E0716]: temporary value dropped while borrowed, noting the temporary creates a temporary which is freed while still in use. The build does not complete.

cargo
error[E0716]: temporary value dropped while borrowed
 --> src/main.rs:3:18
  |
3 |     let s = &String::from("hi").to_uppercase();
  |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ creates a temporary value
  |                                               which is freed while still in use
4 |     println!("{s}");
  |               --- borrow later used here

Common causes

Reference to an unbound temporary

Taking & of an expression that creates a temporary (a function result, a literal-built value) lets the temporary drop at statement end while the reference lives on.

Borrow held past the temporary's scope

A chained or nested expression produces a temporary whose lifetime ends before the borrow is last used (common in match scrutinees and let bindings).

How to fix it

Bind the temporary to a variable first

Give the value a named owner so it lives as long as the reference.

Rust
let owned = String::from("hi").to_uppercase();
let s = &owned;   // owned outlives the borrow
println!("{s}");

Or store the owned value directly

Avoid the reference entirely when you can own the value.

Rust
let s = String::from("hi").to_uppercase();
println!("{s}");

How to prevent it

  • Bind temporaries to a let before borrowing them.
  • Avoid & on chained expressions that build a value inline.
  • Run cargo check locally to catch lifetime errors before CI.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →