Tim*_*ass 4 string loops lifetime rust borrow-checker
我知道String当范围结束loop并且向量input包含 的切片时 会被删除trimmed_text。
我想解决方案是将这些切片的所有权转移到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);
}
Run Code Online (Sandbox Code Playgroud)
编译错误:
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
Run Code Online (Sandbox Code Playgroud)
.split()返回对 a 的引用,String该引用在循环结束时被删除,但您希望input在循环结束后继续存在,因此您应该重构它以保存拥有的值而不是引用。例子:
use std::io;
fn example() {
let mut input: Vec<String>; // changed from &str to String
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");
// map str refs into owned Strings
input = input_text.trim().split(" ").map(String::from).collect();
if input[0] == "Add" && input[2] == "to" {
break;
} else {
println!("Invalid format.");
}
}
println!("{:?}", input);
}
Run Code Online (Sandbox Code Playgroud)