Recursive File Search by Extension

Walk a directory tree without following symlinks, skip hidden entries, and collect regular files matching one extension.

RustData Integrity

Code

rustsnippet
33 lines
use std::path::Path;
use walkdir::{DirEntry, WalkDir};

fn is_hidden(entry: &DirEntry) -> bool {
    entry
        .file_name()
        .to_str()
        .map(|name| name.starts_with('.'))
        .unwrap_or(false)
}

fn find_by_extension(root: &Path, extension: &str) -> Vec<String> {
    WalkDir::new(root)
        .follow_links(false)
        .into_iter()
        .filter_entry(|entry| entry.depth() == 0 || !is_hidden(entry))
        .filter_map(Result::ok)
        .filter(|entry| entry.file_type().is_file())
        .filter(|entry| {
            entry.path().extension().and_then(|ext| ext.to_str()) == Some(extension)
        })
        .map(|entry| entry.path().display().to_string())
        .collect()
}

fn main() {
    let matches = find_by_extension(Path::new("."), "rs");
    for path in matches.iter().take(5) {
        println!("{path}");
    }
    println!("total: {}", matches.len());
}

How the snippet works

Recursive File Search by Extension keeps everything in the functions is_hidden, find_by_extension and main.

Iteration happens inside for path in matches.iter().take(5) — everything outside it runs once.

What to watch for

  • walkdir:: must be installed first — the snippet imports it directly.

Applying it

The main signature reads fn is_hidden(entry: &DirEntry) -> bool

Look for the total: prefixes when the file runs; they tie each line to its step.

main sequences find_by_extension; executing the file runs that flow once.

Statements that matter

for path in matches.iter().take(5) {
println!("{path}");
}
fn is_hidden(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map(|name| name.starts_with('.'))
.unwrap_or(false)
}
.filter(|entry| {
entry.path().extension().and_then(|ext| ext.to_str()) == Some(extension)
})

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `walkdir::` must be present in the project or the import fails at load time.