E0716 rust type_error ai_generated true

error[E0716]: temporary value dropped while borrowed

ID: rust/e0716-temporary-value-dropped

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2024-05-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.65.0 active
1.72.0 active
1.80.0 active

Root Cause

Creating a temporary value (e.g., from a function call) and taking a reference to it, but the temporary is dropped at the end of the statement while the reference outlives it.

generic

中文

创建了一个临时值(例如来自函数调用)并获取了它的引用,但临时值在语句结束时被丢弃,而引用却存活更久。

Official Documentation

https://doc.rust-lang.org/stable/error_codes/E0716.html

Workarounds

  1. 95% success Bind the temporary to a named variable with a lifetime that matches the reference. Example: 'let s = String::from("hello"); let r = &s;' instead of 'let r = &String::from("hello");'
    Bind the temporary to a named variable with a lifetime that matches the reference. Example: 'let s = String::from("hello"); let r = &s;' instead of 'let r = &String::from("hello");'
  2. 90% success Use 'let' with a longer scope: 'let x = foo(); let y = x.bar();' where 'bar' returns a reference.
    Use 'let' with a longer scope: 'let x = foo(); let y = x.bar();' where 'bar' returns a reference.

中文步骤

  1. Bind the temporary to a named variable with a lifetime that matches the reference. Example: 'let s = String::from("hello"); let r = &s;' instead of 'let r = &String::from("hello");'
  2. Use 'let' with a longer scope: 'let x = foo(); let y = x.bar();' where 'bar' returns a reference.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Adding 'clone()' to the temporary without storing it in a variable — the clone still creates a temporary that is dropped.

  2. 90% fail

    Adding 'unsafe' block to extend lifetime — unsafe doesn't change lifetimes and is incorrect.