How to keep using a value after pushing it into a vector?

Viewed 130

So I want to keep using a value after pushing it into a vector, but when I add it to the vector it takes ownership control over the variable, so when I want to make reference to it again I can't. How should I approach this scenario?

fn scan_recursive(dir: &Path) -> io::Result<Vec<PathBuf>> {
    let mut files = Vec::new(); // Create a mutable vector to store the files.

    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();

        if path.is_file() {
            files.push(path);
        }

        if path.is_dir() { // ERROR: path is no longer valid
            files.append(&mut scan_recursive(&path)?);
        }
    }

    Ok(files)
}
1 Answers

The problem is that the compiler does not know if the first if is executed and cannot tell if the path variable is consumed or not, so it assumes that it always is, and the lifetime of path ends after the push to the vector.

Given that your two ifs are mutually exclusive (the path is either a file or a directory) you can use if ... else, which will let the compiler deduce that if the path is not a file, the variables has not been consumed in the if branch and it will still be available in the else branch.

if path.is_file() {
  files.push(path);
}
else if path.is_dir() {
  files.append(&mut scan_recursive(&path)?);
}
Related