Warning
This post was published 31 days ago. The information described in this article may have changed.
I am writing a small bit of code to simply list out all the files in a directory, and as far as I can tell, this seems like the correct way to do that:
fn get_files(p: &Path) -> Result<Vec<PathBuf>, io::Error> {
read_dir(p)?
.into_iter()
.map(|f| f.map(|f| f.path()))
.filter(|f| f.as_ref().is_ok_and(|f| f.is_file()))
.collect()
}
However, my naive rust-beginner brain would have preferred to write:
fn get_files(p: &Path) -> Result<Vec<PathBuf>, io::Error> {
read_dir(p)?
.into_iter()
.map(|f| f?.path())
.filter(|f| f?.is_file())
.collect()
}
If I understand the compiler messages, this is not allowed because then the closures are then returning PathBuff and bool rather than Results.
Given that, there a better/more ergonomic way to approach this that I'm missing (especially since I'm collecting the Results anyway), or is this the preferred approach?
Thank you for any help!
2 posts - 2 participants
🏷️ rust_feed