'Borrowed value does not live long enough' when reading file content and returning a vector of structs with the data from that file

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.

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 {


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.

Since your User types uses the non-owned &str type, the user can only exist while the owner of the string data is alive. In this case, the owner of the string data is the contents variable, which is destroyed at the end of get_all.

To fix it, change it to use the owned String type instead.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.