tl;dr error[E0716]: temporary value dropped while borrowed
是一个常见且难以解决的问题,是否有一致的解决方案?
我遇到了令人困扰的 rustc 错误。
error[E0716]: temporary value dropped while borrowed
...
creates a temporary which is freed while still in use
在Stackoverflow上搜索,有许多关于这个rust错误error[E0716]
的问题。
示例代码
一个简洁的代码示例来演示问题 (rust playground):
type Vec1<'a> = Vec::<&'a String>;
fn fun1(s1: &String, v1: &mut Vec1) {
v1.insert(0, &s1.clone());
}
fn main() {
let mut vec1 = Vec::new();
let str1 = String::new();
fun1(&str1, &mut vec1);
}
结果:
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:4:19
|
3 | fn fun1(s1: &String, v1: &mut Vec1) {
| -- has type `&mut Vec<&'1 String>`
4 | v1.insert(0, &s1.clone());
| --------------^^^^^^^^^^-- temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| argument requires that borrow lasts for `'1`
For more information about this error, try `rustc --explain E0716`.
我的理解
根据语句v1.insert(0, &s1.clone());
,
s1.clone()
会创建一个新的String
,并使用堆作为存储空间。然后将这个新克隆的String
的引用(添加了&
)传递给调用v1.insert
的函数。因此,在函数fun1
返回后,新的String
数据和传递给insert
的引用将保留。
但是,Rust编译器报告s1.clone()
仅仅是临时的。
类似的链接问题
以下是类似问题的链接,版本不一定相同,但有点冗长(我个人认为)。
- 错误[E0716]: 借用时临时值被丢弃
- 为什么借用临时值是合法的?
- 借用时临时值被丢弃
- 借用时临时值被丢弃(E0506)
- 使用string.replace()时出现“借用时临时值被丢弃”
- 错误[E0716]: 借用时临时值被丢弃
- 如何解决“借用时临时值被丢弃”问题
- 迭代器查找,临时值在借用后被丢弃
- 使用捕获闭包时出现“借用时临时值被丢弃”
- Rust引用在仍被借用时被丢弃
- 对“temporary value dropped here while still borrowed”感到困惑[duplicate]
- 使用构建器模式时,“borrowed value does not live long enough”
- 构建器模式 - 借用的值未能存活足够长的时间
- 由于借用的值未能存活足够长的时间,无法编译Rust构建器模式[duplicate]
- 借用的值未能存活足够长的时间