I'm trying to get the path to the first entry in a directory, but it seems the read_dir
response type ReadDir
is an iterator and cannot be indexed, e.g.
fn get_single_file_or_none(dir_path: &PathBuf) -> Result<Option<PathBuf>, io::Error> {
let entries = fs::read_dir(dir_path)?;
if entries.count() == 1 {
let path = entries[0].path();
// ^^ cannot index into a value of type `std::fs::ReadDir`
return Ok(path);
}
return Ok(None);
}
How can I get the path to the first (and in this case, the only) entry in the directory?
I cant start iterating over the entries, knowing there's only one, and return the first one I hit. Is that the only solution? e.g.
if entries.count() == 1 {
for entry_res in entries {
return match entry_res {
Err(er) => Err(er),
Ok(en) => Ok(Some(en.path())),
};
}
}
itertools
has the handy exactly_one()
function:
use itertools::Itertools;
fn get_single_file_or_none(dir_path: &PathBuf) -> Result<Option<PathBuf>, io::Error> {
let entries = fs::read_dir(dir_path)?;
Ok(entries.exactly_one().ok().transpose()?.map(|it| it.path()))
}
This is more efficient than count()
, since it will only read the directory once.