【发布时间】:2021-05-29 14:58:14
【问题描述】:
我还在学习 Rust 并且有以下代码。
use std::collections::BTreeMap;
#[derive(Debug)]
struct MyStruct {
a: String,
b: String,
}
fn main() {
let mut hash = BTreeMap::new();
let data = vec![
MyStruct {
a: "entry1".to_string(),
b: "entry1 body".to_string(),
},
MyStruct {
a: "entry2".to_string(),
b: "entry2 body".to_string(),
}
];
let re = regex::Regex::new(r#".(\d)"#).unwrap();
for item in &data {
for m in re.captures_iter(&item.b) {
hash.insert(&m[1].parse::<i32>().unwrap(), &item.a);
}
}
println!("{:#?}", hash);
}
它会产生错误:
error[E0716]: temporary value dropped while borrowed
--> src\main.rs:26:26
|
26 | hash.insert(&m[1].parse::<i32>().unwrap(), &item.a);
| ---- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| | |
| | creates a temporary which is freed while still in use
| borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
修复它的正确方法是什么?我尝试将&m[1].parse::<i32>().unwrap() 放入变量中,但无济于事。
【问题讨论】:
-
简单;不要借它!
hash.insert(m[1].parse::<i32>().unwrap(), &item.a);
标签: rust borrow-checker