I have a string that was read from a file. For each line, I would like to split the string and save the split strings to memory as vectors:
use std::io::{BufReader, BufRead};
fn main() {
let s = r#"line1,line
line2,line2"#;
let reader = BufReader::new(s.as_bytes());
let mut out = Vec::new();
let iter = reader
.lines()
.map(|line| line.unwrap().to_string())
.collect::<Vec<_>>();
for x in iter {
let split = x.split(',').collect::<Vec<_>>();
out.push(split);
}
}
Error message
error[E0597]: `x` does not live long enough
--> src/main.rs:18:6
|
16 | let split = x.split(',').collect::<Vec<_>>();
| - borrow occurs here
17 | out.push(split);
18 | }
| ^ `x` dropped here while still borrowed
19 | }
| - borrowed value needs to live until here
iter, you transfer ownership of theVecand the strings inside it to theforloop.splitreturns a reference to the string, but the string will be deallocated ("dropped") at the end of each loop iteration, invalidating any references. Instead of consumingiterduring iteration, iterate over references to it. One example