【发布时间】:2021-02-11 20:06:52
【问题描述】:
我知道当loop 的范围结束并且向量input 包含trimmed_text 的切片时,String 会被删除。
我想解决方案是将这些切片的所有权转移到input 或类似的东西。如何做到这一点?
use std::io;
fn main() {
let mut input: Vec<&str>;
loop {
let mut input_text = String::new();
println!("Type instruction in the format Add <name> to <department>:");
io::stdin()
.read_line(&mut input_text)
.expect("failed to read from stdin");
let trimmed_text: String = input_text.trim().to_string();
input = trimmed_text.split(" ").collect();
if input[0] == "Add" && input[2] == "to" {
break;
} else {
println!("Invalid format.");
}
}
println!("{:?}", input);
}
编译错误:
error[E0597]: `trimmed_text` does not live long enough
--> src/main.rs:14:17
|
14 | input = trimmed_text.split(" ").collect();
| ^^^^^^^^^^^^ borrowed value does not live long enough
...
21 | }
| - `trimmed_text` dropped here while still borrowed
22 |
23 | println!("{:?}", input);
| ----- borrow later used here
【问题讨论】:
-
我认为只需将您的
input从持有&str更改为拥有的字符串就可以了。您可能还需要将修剪和拆分的文本显式复制到input -
除了改变类型外,还需要显式地将字符串切片转为字符串,例如使用
.map(String::from)或类似的。
标签: string loops rust lifetime borrow-checker