0

Within my cd function, I want to retrieve an element out of a HashMap and assign this reference to cursor.

The rust compiler complains that the reference that I retrieve out of the hashmap does not live long enough. Is that due to my declared live times? I thought that in this scenario I can declare data as 'static, but apparently, structs are not supposed to be static.

This is a smaller reproduction of my code:

use std::{
    collections::HashMap,
    sync::{Mutex, MutexGuard},
};

#[derive(Debug)]
struct DataEntry {
    name: String,
}

type DataCollection = HashMap<String, DataEntry>;
fn main() {
    let data: Mutex<HashMap<String, DataEntry>> = Mutex::new(DataCollection::new());
    let input = "
      cd /
      ls 
      dir d
      dir e
      dir o
    ";
    let lines: Vec<Vec<&str>> = input
        .lines()
        .map(|line| line.trim().split(" ").collect::<Vec<&str>>())
        .collect();
    let cursor: Option<&DataEntry> = None;

    for segments in lines {
        match segments[0] {
            "cd" => {
                let data = data.lock().unwrap();
                cd(segments[1].to_owned(), data, cursor);
            }
            "dir" => {}
            _ => {}
        }
    }
}

fn cd<'a, 'b>(
    name: String,
    mut data: MutexGuard<'a, DataCollection>,
    mut cursor: Option<&'a DataEntry>,
) {
    cursor = Some(
        data.entry(name.clone())
            .or_insert(DataEntry { name: name.clone() }),
    );
}

Error:

error[E0597]: `data` does not live long enough
  --> src/bin/test2.rs:45:9
   |
39 | fn cd<'a, 'b>(
   |       -- lifetime `'a` defined here
...
45 |         data.entry(name.clone())
   |         ^^^^^^^^^^^^^^^^^^^^^^^^
   |         |
   |         borrowed value does not live long enough
   |         argument requires that `data` is borrowed for `'a`
...
48 | }
   | - `data` dropped here while still borrowed

oliverwebr
  • 459
  • 3
  • 13

0 Answers0