2

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Teo
  • 558
  • 1
  • 4
  • 10
  • 2
    *A temporary value is created and dropped in the map*; yes, that's right... so **don't do that**. `.map(|f| f.metadata().unwrap())` instead. If you *truly* need a `Vec[&Metadata]`, you will need to build it based on the intermediate `Vec`. Otherwise, you'd have references to invalid memory. – Shepmaster Sep 01 '17 at 20:30
  • 1
    @Shepmaster Thanks, that allowed me to fix it – Teo Sep 01 '17 at 20:40

0 Answers0