Returning a value borrowed from inside a closure

478 Views Asked by At

I'm looking to get a Vec<&Metadata> from files:

use std::fs::File;

fn example(files: Vec<&File>) {
    let files_metadata: Vec<_> = files
        .iter()
        .map(|f| &f.metadata().unwrap())
        .collect();
}

A temporary value is created and dropped in the map, it needs to live as long as files_metadata.

error[E0597]: borrowed value does not live long enough
 --> src/main.rs:6:39
  |
6 |         .map(|f| &f.metadata().unwrap())
  |                   --------------------^
  |                   |                   |
  |                   |                   temporary value dropped here while still borrowed
  |                   temporary value created here
7 |         .collect();
8 | }
  | - temporary value needs to live until here
0

There are 0 best solutions below