I recently started learning rust and decided to make a simple project to manipulate CSV data.
When reading the data from the CSV file, I started getting this error and I just can't wrap my head around it.
#[derive(Debug)]
pub struct User<'a> {
pub first_name: &'a str,
pub last_name: &'a str,
}
pub trait Entity {
fn get_all() -> Vec<Self> where Self: Sized;
}
impl Entity for User<'_> {
fn get_all() -> Vec<Self> where Self: Sized {
let mut users = vec![];
let mut file = File::open("users.csv").expect("File not found");
let mut contents = String::new();
file.read_to_string(&mut contents).expect("Failed to read file");
for line in contents.lines() {
let mut cols = line.split(",");
let first_name = cols.next().unwrap();
let last_name = cols.next().unwrap();
let role = cols.next().unwrap();
users.push(Self {
first_name,
last_name,
});
}
users
}
}
Here is the error:
error[E0597]: `contents` does not live long enough
--> src/main.rs:26:21
|
19 | fn get_all() -> Vec<Self> where Self: Sized {
| --------- return type is Vec<User<'1>>
...
26 | for line in contents.lines() {
| ^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
32 | first_name,
| ---------- this usage requires that `contents` is borrowed for `'1`
...
38 | }
| - `contents` dropped here while still borrowed
I understand that the content gets deallocated after the for loop, and that the User is referencing something that lives inside that content, but I don't really know how to fix that.