I've been looking in the rust, as it sounds quite interesting, although, some of the concepts are but hard to wrap my head around, or at least, how to use them correctly.
Take for instance the following function:
pub fn get_records(filename: &str) -> std::io::Result<Vec<[&str; 3]>> {
let mut objs: Vec<[&str; 3]> = Vec::new();
let mut rdr = csv::Reader::from_path(filename)?;
for result in rdr.records() {
let record = result?;
let mut obj: [&str; 3] = ["EMPTY", "EMPTY", "EMPTY"];
for field in record.iter().enumerate() {
obj[field.0] = field.1;
}
//println!("{:?}", obj);
objs.push(obj);
}
Ok(objs)
}
I want it to read a csv file, and put each (3, specifically) field of one entry into an array and that array into a vector, so like:
vec![
[field, field, field],
[field, field, field]
]
The function may be not the best code, but it does this. Here, the problem lies: when trying to return the vector to my main function, I get:
error[E0515]: cannot return value referencing local variable `record`
--> src/parse.rs:18:5
|
12 | for field in record.iter().enumerate() {
| ------ `record` is borrowed here
...
18 | Ok(objs)
| ^^^^^^^^ returns a value referencing data owned by the current function
So, I get why rust does ownership like this, but I still want my function to be able to return this vector.
How would I go about refactoring my function to do this?