我只是想做这样的事情:
fn main() {
let mut points: Vec<(&str, &str)> = Vec::new();
let existing: Vec<(String, String)> = Vec::new();
for t in existing {
points.push((&t.0[..], &t.1[..]));
}
}
出现错误:
error[E0597]: `t.0` does not live long enough
--> src/main.rs:6:23
|
5 | for t in existing {
| - binding `t` declared here
6 | points.push((&t.0[..], &t.1[..]));
| ------ ^^^ borrowed value does not live long enough
| |
| borrow later used here
7 | }
| - `t.0` dropped here while still borrowed
我如何在 Rust 中做到这一点?
生命周期从变量声明开始。由于
points
变量是在 existing
变量之前创建的,因此 points
不允许有任何对 existing
的引用,因为 existing
将在 points
之前被删除。
第二个问题是您正在迭代值,这将进一步限制循环体的字符串的生命周期。
简单的解决方案是交换两个声明并将循环更改为迭代引用而不是值:
let existing : Vec<(String, String)> = Vec::new();
let mut points : Vec<(&str, &str)> = Vec::new();
for t in &existing {
points.push((&t.0, &t.1));
}