0

I'm new to rust and trying to collect files into a string vector.

use glob::glob;
use std::env;

fn main() {
    let mut file_names: Vec<&str> = Vec::new();

    let cwd = env::current_dir().unwrap();

    for entry in glob(cwd.to_str().unwrap()).expect("Failed to read directory.") {
        match entry {
            Ok(file) => {
                println!("{:?}", file.file_name());
                let file_name = file.file_name().unwrap().to_str();
                file_names.push(file_name.unwrap());
            }
            Err(e) => println!("{:?}", e),
        }
    }
}

Receiving the following error.

error[E0597]: `file` does not live long enough
  --> src/main.rs:13:33
   |
13 |                 let file_name = file.file_name().unwrap().to_str();
   |                                 ^^^^ borrowed value does not live long enough
14 |                 file_names.push(file_name.unwrap());
   |                 ---------- borrow later used here
15 |             }
16 |             Err(e) => println!("{:?}", e),
   |               - `file` dropped here while still borrowed

error: aborting due to previous error

I'm not sure how to push the file names into the vector. Thanks!

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
hooinator
  • 339
  • 2
  • 13
  • The file names in your loop are all temporary variables, so you can't store references to them in a vector which outlives the loop. Instead, perhaps store `String`s in the vector? – Peter Hall Feb 28 '20 at 16:06
  • Thanks @PeterHall that did it!!! – hooinator Feb 28 '20 at 16:11

1 Answers1

0

Thanks to @PeterHall this is the corrected code.

use glob::glob;
use std::env;

fn main() {
    let mut file_names: Vec<String> = Vec::new();

    let cwd = env::current_dir().unwrap();

    for entry in glob(cwd.to_str().unwrap()).expect("Failed to read logs directory.") {
        match entry {
            Ok(file) => {
                println!("{:?}", file.file_name());
                let file_name = file.file_name().unwrap().to_str().unwrap();
                file_names.push(file_name.to_string());
            }
            Err(e) => println!("{:?}", e),
        }
    }

    for file_name in file_names {
        println!("{:?}", file_name);
    }
}
hooinator
  • 339
  • 2
  • 13