Sorting Glob Result


How does one sort the results of a glob before processing in the given example (i.e. I want to sort files by some sort of filter)

use glob::glob;

for entry in glob("/media/**/*.jpg").expect("Failed to read glob pattern") {
 match entry {
     Ok(path) => println!("{:?}", path.display()),
     Err(e) => println!("{:?}", e),


You can collect the results of the glob into a Vec and sort that:

let mut v: Vec<_> = glob("/media/**/*.jpg").expect("Failed to read glob pattern").collect();
v.sort_by(...); // or sort_unstable_by() or any other sorting flavor
for entry in v {


Awesome thanks. The sorting is a little odd though?

 files.sort_by(|a, b| a.unwrap().to_str().unwrap().cmp(b.unwrap().to_str().unwrap()));


Oh, that iterator returns a Result. You can collect into a Result<Vec<PathBuf, GlobError>>:

let mut v: Result<Vec<_>, _> = glob("/media/**/*.jpg").expect("Failed to read glob pattern").collect();
let v = v.unwrap(); // now you have a Vec<PathBuf>
for entry in v {

Collecting into a Result<Vec<PathBuf>, GlobError>> here means that if any of the glob iterator items is an error, then you’ll get an Err value back; if no errors encountered, then you get the Ok variant with the PathBufs.