use the iteration object multiple times (Rust)

Viewed 45

I'm new to rust. I need to get a list of files and directories in a folder, however I can't access the iteration object more than once.

Of course, this can be done using else, but I would like to know what to do in such a situation.

for d in fs::read_dir("./").unwrap() {
    if d.unwrap().path().is_dir() {
        continue;
    } else if d.unwrap().path().is_file() { //except here
        continue;         
    }
1 Answers

I'm new to rust. I need to get a list of files and directories in a folder, however I can't access the iteration object more than once.

You can understand why, and how to fix it, by looking at the documentation. Specifically the self types:

read_dir returns an iterator of Result<DirEntry>, so that's what d is.

Result::unwrap takes self, so it consumes the result itself, meaning after the first call to d.unwrap() there is no d anymore.

Your solutions then are:

  • since path, is_dir, and is_file all take &self as ShadowRanger notes you can just store the unwrapped DirEntry, or the paths
  • alternatively, you can use Result::as_ref to get a Result<&DirEntry>, which you can then unwrap to get an &DirEntry of which you can get the path, this only needs a &Result, so it does not consume the Result itself
Related