Here is segment I've a problem with, basically just pushing a &str to Vec<&str> in the loop
fn main() {
let mut accounting = vec!["Alice", "Ben"];
loop {
let mut add_input = String::from("");
io::stdin()
.read_line(&mut add_input)
.expect("Failed to read line");
let add_vec: Vec<&str> = add_input.trim()[..].split_whitespace().collect();
if add_vec.len() < 1 {
println!("Incorrect input, try again");
continue;
}
let person = add_vec[0];
accounting.push(person);
}
}
let add_vec: Vec<&str> = add_input.trim()[..].split_whitespace().collect();
- here's where I get "borrowed value does not live long enough".
I was able to make my code work by changing target vector signature from Vec<&str>
to Vec<String>
and pushing not a &str but &str.to_string()
I understand that pushing a &str bacibally making it invalid to for the scope that .push was called in, but while that is happening right at the end of the loop - why is that a problem?
The error give is:
$ rustc main.rs
error[E0597]: `add_input` does not live long enough
--> main.rs:14:34
|
14 | let add_vec: Vec<&str> = add_input.trim()[..].split_whitespace().collect();
| ^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
22 | accounting.push(person);
| ----------------------- borrow later used here
23 | }
| - `add_input` dropped here while still borrowed
error: aborting due to previous error
For more information about this error, try `rustc --explain E0597`.