我真的很新手 Rust,我在解决这个错误时遇到了麻烦,但只有当我注释掉 while 语句时才会发生,基本上我正在从控制台请求值并将其存储在 HashMap 中:
use std::collections::HashMap;
use std::io;
fn main() {
let mut customers = HashMap::new();
let mut next_customer = true;
while next_customer {
let mut input_string = String::new();
let mut temp_vec = Vec::with_capacity(3);
let mut vec = Vec::with_capacity(2);
println!("Insert new customer f.e = customer id,name,address:");
io::stdin().read_line(&mut input_string);
input_string = input_string.trim().to_string();
for s in input_string.split(",") {
temp_vec.push(s);
}
vec.push(temp_vec[1]);
vec.push(temp_vec[2]);
let mut key_value = temp_vec[0].parse::<i32>().unwrap();
customers.insert(key_value, vec);
next_customer = false;
}
println!("DONE");
}
代码出现了错误。
error[E0597]: `input_string` does not live long enough
--> src/main.rs:14:18
|
14 | for s in input_string.split(",") {
| ^^^^^^^^^^^^ borrowed value does not live long enough
...
20 | customers.insert(key_value, vec);
| --------- borrow later used here
21 | next_customer = false;
22 | }
| - `input_string` dropped here while still borrowed
vec
最终包含对input_string
切片的引用,这些切片仅在循环迭代结束时存在,但您尝试将其添加到超出循环生存期的customers
中。 - Sven Marnachinput_string.split(",").collect()
。更多信息请查看链接:https://users.rust-lang.org/t/solved-string-lifetime-error-borrowed-value-does-not-live-long-enough/5233 - num8ervec.push(temp_vec[1].to_owned())
,并对接下来的行进行类似操作。 - Sven Marnachtrim()
和split()
方法不会分配新的字符串 - 它们返回指向传入的字符串的切片引用,即返回值的类型为&str
而不是String
。这些切片只在它们所指向的字符串存在期间才存在,也就是在此情况下循环迭代结束之前。 - Sven Marnach