I'm learning Rust. Could you share some tips for improving this code so it's more idiomatic and functional? I would prefer to stick to the standary library, and avoid unnecessary sorting or memory allocations.
fn first_file_in_dir(dir_path: &Path, extension: &str) -> Result<PathBuf, io::Error> {
let mut matching_path = None;
for entry in fs::read_dir(dir_path)? {
let entry = entry?;
if !entry.file_type()?.is_file() {
continue;
}
let path = entry.path();
if !path.extension().is_some_and(|x| x == extension) {
continue;
}
if let Some(ref mut matching_path) = matching_path {
if path < *matching_path {
*matching_path = path;
}
} else {
matching_path = Some(path);
}
}
if let Some(matching_path) = matching_path {
Ok(matching_path)
} else {
Err(io::Error::new(io::ErrorKind::NotFound,
format!("No *.{} file in {}", extension, dir_path.to_string_lossy())))
}
}
The function returns the first file with a given extension inside a directory. Because the order of items from fs::read_dir()
is platform dependent, it iterates over all files and picks the top one by name. Any I/O errors are propagated to the caller.
Thanks!