I wrote a method to read the first line of a CSV file. It performs a split(',') and collects() into a vector<&str>. I can println! elements of the vector. But, when I try to bind a field of the struct to an element of the Vec, I receive a lifetime error. The error states I am borrowing when I thought I am moving. I need help understanding what my error is:
#[derive(Debug)]
struct Aircraft <'a>{
prod_no:&'a str,
tail_no:&'a str,
top_lvl_software:&'a str,
cmf_id:&'a str,
}
impl <'a> Aircraft <'a>{
fn new() -> Self {
Self {
prod_no: "",
tail_no: "",
top_lvl_software: "",
cmf_id: "",
}
}
fn from_file(&mut self, filename: &str) {
let mut file_reader = BufReader::new(
File::open(filename)
.expect("File does not exist")
);
let mut line_iter = file_reader.lines().map(|line| line.unwrap());
let line: String = match line_iter.next() {
None => panic!("didn not parse"),
Some(t) => t,
};
let mut header: Vec<&str> = line
.split(',')
.collect();
println!("BufRead = {}", header[5]);
self.set_prod_no (header[5]);
}
fn set_prod_no(&mut self, prod_no: &'a str) {
self.prod_no = prod_no;
}
}
My compiler error:
error[E0597]: line does not live long enough
--> src\main.rs:89:37
|
66 | impl <'a> Aircraft <'a>{
| -- lifetime 'a defined here
...
89 | let mut header: Vec<&str> = line
| ^^^^ borrowed value does not live long enough
...
95 | self.set_prod_no (header[5]);
| ---------------------------- argument requires that line is borrowed for 'a
96 | }
| - line dropped here while still borrowed
I know it's something simple....I just can't see it.
Thanks!