Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Get All Files With A Certain Extension Recursively In Rust

Code

//! ```cargo
//! [package]
//! edition = "2021"
//! [dependencies]
//! walkdir = "2"
//! ```


use std::path::PathBuf;
use walkdir::WalkDir;


fn get_files_in_dir_matching_extension_recursively(dir: &str, exts: Vec<&str>) -> Vec<PathBuf> {
    WalkDir::new(dir)
        .into_iter()
        .filter(|e| 
            match e.as_ref().unwrap().path().extension() {
                Some(x) => exts.contains(&x.to_str().unwrap()),
                None => false
    }).map(|e| e.unwrap().into_path()).collect()
}


fn main() {
    let files = list_files(
        "recursive_test/example",vec!["txt"]
    );
    dbg!(files);
}

Results

[_active_nvim_run:15] files = [
    "recursive_test/example/.hidden_file_1.txt",
    "recursive_test/example/a/2.txt",
    "recursive_test/example/a/c/4.txt",
    "recursive_test/example/.hidden_file_2.txt",
    "recursive_test/example/1.txt",
    "recursive_test/example/b/3.txt",
]