Use of moved value error

Hi, I'm trying to make a very simple function that simply returns a vec of all the files in a directory. However, I can't seem to get it to work because I get the error:

for entry in &WalkDir::new(rootdir).into_iter().filter_map(|e| e.ok()) {
         -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         |
         `&std::iter::FilterMap<walkdir::IntoIter, [closure@src/main.rs:12:64: 12:74]>` is not an iterator
         help: consider removing the leading `&`-reference

And my code is:

 pub fn listdirs(rootdir: &str) -> Vec<PathBuf> {

    let mut dirlist: Vec<PathBuf> = Vec::new();

    for entry in WalkDir::new(rootdir).into_iter().filter_map(|e| e.ok()) {
        if entry.into_path().is_file(){
            dirlist.push(entry.into_path())
        }
    }
     return dirlist;
}

Normally I am able to fix the use of moved value errors with ease, since it is just basic ownership, but I'm at a loss for how to fix this one.

Have a look at the if entry.into_path() { dirlist.push(entry.into_path()) } condition. The entry.into_path() method will consume the entry and give you its location as a PathBuf. That means entry won't be accessible when you try to push it onto the dirlist.

I'd suggest extracting the path into a local variable above the if statement.

pub fn listdirs(rootdir: &str) -> Vec<PathBuf> {
    let mut dirlist = Vec::new();

    for entry in WalkDir::new(rootdir).into_iter().filter_map(|e| e.ok()) {
        let path = entry.into_path();

        if path.is_file(){
            dirlist.push(path)
        }
    }

     dirlist
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.