#`buffer` does not live long enough

12 messages · Page 1 of 1 (latest)

lone falcon
#

So I've got this code right now

  pub struct WadRework<'a> {
      pub version: u32,
      pub file_count: u32,
      pub files: HashMap<String, FileRecord>,
      pub buffer: &'a mut Vec<u8>,
  }

  let mut buffer = std::fs::read("CSR.wad").unwrap_or(vec![]);
  let mut wad = WadRework::new(&mut buffer).unwrap();

    thread::spawn(move || {
        for (_, v) in &wad.files.clone() {
            let buf = wad.open_file(v.file_name.as_str());
            let path = path.join(&v.file_name);
            let prefix = path.parent().unwrap();
            create_dir_all(&prefix).unwrap();
            std::fs::write(&path, buf).unwrap(); // Write to the file
        }
    });

but it tells me that

error[E0597]: `buffer` does not live long enough
  --> src\main.rs:19:34
   |
19 |     let mut wad = WadRework::new(&mut buffer).unwrap();
   |                   ---------------^^^^^^^^^^^-
   |                   |              |
   |                   |              borrowed value does not live long enough
   |                   argument requires that `buffer` is borrowed for `'static`
...
40 | }
   | - `buffer` dropped here while still borrowed


``` And I've alread tried to fix it using the `'static` docs article but it doesn't want to work
paper bay
#

'a might not live for as long as 'static but the thread might live for 'static/the whole program

#

is there a reason you need to store a reference?

lone falcon
#

the buffer? I thought it would increase the performance 😄

paper bay
#

just move it into the struct

#

it is recommended to only use references in struct if you absolutely need to

lone falcon
lone falcon
paper bay
#

dealing with owned types is much simpler

#

and it makes more sense logically for the struct to own the data it stores

#

only in specific situations does it borrow