This is similar to the accepted answer but with a little error handling added. In most situations you would want to report an error to the user, or propagate errors to the caller in a library. I've used the answer at How do I stop iteration and return an error when Iterator::map returns a Result::Err? to collect a iterator of Results into a Result<vec<_>, _>.
I'm supplying an additional answer so others searching the same problem get something they may find more practical in a program where errors are handled.
use std::fs::{read_dir, DirEntry};
use std::io;
use std::path::Path;
fn main() {
for path in read_dir_sorted("/").expect("IO error reading /") {
println!("Name: {}", path.path().display())
}
}
fn read_dir_sorted<P: AsRef<Path>>(path: P) -> Result<Vec<DirEntry>, io::Error> {
let mut paths = read_dir(path)?
.collect::<Result<Vec<_>, _>>()?;
paths.sort_by_key(|de| de.file_name());
Ok(paths)
}