I'm trying to parse a file and return Vec<Vec<&str>>
from a function. But I'm getting borrowed value error inside the file read loop while pushing to the vector.
use std::io::{self, BufReader, prelude::*};
use std::fs::File;
fn read() -> Vec<Vec<&'static str>> {
let file = File::open("~/test").expect("failed to read file");
let reader = BufReader::new(file);
let mut main_vector: Vec<Vec<&str>> = Vec::new();
for line in reader.lines() {
match line {
Ok(v) => {
let mut sub_vector: Vec<&str> = Vec::new();
for element in v.split_whitespace().collect::<Vec<&str>>() {
sub_vector.push(element);
}
main_vector.push(sub_vector);
},
Err(e) => panic!("failed to parse: {:?}", e),
}
}
//return main_vector;
}
Here's the compiler error:
error[E0597]: `v` does not live long enough
--> src/main.rs:67:32
|
67 | for element in v.split_whitespace().collect::<Vec<&str>>() {
| ^ borrowed value does not live long enough
...
70 | main_vector.push(sub_vector);
| -------------- borrow later used here
71 | },
| - `v` dropped here while still borrowed
I think it's about the references and borrowing but still I'm having hard time to figure this out.