I want to create and return my headers
& statements
from a function. The statements
is a vector each element borrows a value from the headers
like so:
use csv::{Reader, StringRecord};
use std::{collections::VecDeque, error::Error};
fn main() {
let (headers, statements) = run().unwrap();
}
fn run<'a>() -> Result<(StringRecord, VecDeque<Statement<'a>>), Box<dyn Error>> {
let mut rdr = Reader::from_path("input.csv")?;
let headers = rdr.headers()?.clone();
let mut statements = VecDeque::new();
for result in rdr.records() {
let record = result?;
for (i, v) in record.iter().enumerate() {
statements.push_back(Statement::new(&headers[i]));
}
}
Ok((headers, statements))
}
struct Statement<'a> {
label: &'a str,
}
impl<'a> Statement<'a> {
fn new(label: &'a str) -> Self {
Statement { label }
}
}
There're errors with the above snippet, could you please explain why and show me the way to fix this?
error[E0515]: cannot return value referencing local variable `headers`
--> src/main.rs:21:5
|
17 | statements.push_back(Statement::new(&headers[i]));
| ------- `headers` is borrowed here
...
21 | Ok((headers, statements))
| ^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
error[E0505]: cannot move out of `headers` because it is borrowed
--> src/main.rs:21:9
|
8 | fn run<'a>() -> Result<(StringRecord, VecDeque<Statement<'a>>), Box<dyn Error>> {
| -- lifetime `'a` defined here
...
17 | statements.push_back(Statement::new(&headers[i]));
| ------- borrow of `headers` occurs here
...
21 | Ok((headers, statements))
| ----^^^^^^^--------------
| | |
| | move out of `headers` occurs here
| returning this value requires that `headers` is borrowed for `'a`
Some errors have detailed explanations: E0505, E0515.
For more information about an error, try `rustc --explain E0505`.
warning: `rust` (bin "rust") generated 3 warnings
error: could not compile `rust` due to 2 previous errors; 3 warnings emitted