rust 33 lines · 8 steps

Recursive file search by extension in Rust

A public entry point normalizes the query, then a recursive helper walks the directory tree collecting matching paths.

Explained by highlit
1use std::fs;
2use std::io;
3use std::path::{Path, PathBuf};
4 
5pub fn find_by_extension<P: AsRef<Path>>(root: P, ext: &str) -> io::Result<Vec<PathBuf>> {
6 let mut matches = Vec::new();
7 let ext = ext.trim_start_matches('.');
8 walk(root.as_ref(), ext, &mut matches)?;
9 Ok(matches)
10}
11 
12fn walk(dir: &Path, ext: &str, out: &mut Vec<PathBuf>) -> io::Result<()> {
13 for entry in fs::read_dir(dir)? {
14 let entry = entry?;
15 let path = entry.path();
16 let file_type = entry.file_type()?;
17 
18 if file_type.is_symlink() {
19 continue;
20 }
21 
22 if file_type.is_dir() {
23 walk(&path, ext, out)?;
24 } else if path
25 .extension()
26 .and_then(|e| e.to_str())
27 .map_or(false, |e| e.eq_ignore_ascii_case(ext))
28 {
29 out.push(path);
30 }
31 }
32 Ok(())
33}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Accepting `AsRef<Path>` lets callers pass strings, `PathBuf`, or `Path` without extra conversions.
  2. 2Threading a `&mut Vec` through recursion accumulates results without allocating at every level.
  3. 3The `?` operator propagates I/O errors cleanly so the walk aborts on the first failure.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Recursive file search by extension in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code