我了解 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);
}
编译错误:
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
最佳答案
.split()
返回对 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);
}
关于string - "Borrowed value does not live long enough", 在循环中使用时丢弃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66162034/