E0716 rust type_error ai_generated true

错误[E0716]: 临时值在被借用时被丢弃

error[E0716]: temporary value dropped while borrowed

ID: rust/e0716-temporary-value-dropped

其他格式: JSON · Markdown 中文 · English
90%修复率
85%置信度
1证据数
2024-05-20首次发现

版本兼容性

版本状态引入弃用备注
1.65.0 active
1.72.0 active
1.80.0 active

根因分析

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

English

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

官方文档

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

解决方案

  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.

无效尝试

常见但无效的做法:

  1. 70% 失败

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

  2. 90% 失败

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