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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Accepting `AsRef<Path>` lets callers pass strings, `PathBuf`, or `Path` without extra conversions.
- 2Threading a `&mut Vec` through recursion accumulates results without allocating at every level.
- 3The `?` operator propagates I/O errors cleanly so the walk aborts on the first failure.
Related explainers
javascript
const express = require('express'); const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware'); const router = express.Router();
Building an API gateway proxy in Express
reverse-proxy
middleware
api-gateway
Intermediate
6 steps
rust
use axum::{ extract::{FromRequestParts, Query}, http::{request::Parts, StatusCode}, };
Building a custom Axum extractor for query filters
extractors
query-parsing
enums
Intermediate
8 steps
python
import asyncio from dataclasses import dataclass import aiohttp
Bounded-concurrency HTTP fetching with asyncio
async
concurrency
semaphore
Intermediate
8 steps
rust
use std::sync::Arc; use axum::{ extract::{Multipart, State}, http::StatusCode,
Throttling file uploads in Axum with a Semaphore
concurrency
backpressure
multipart
Advanced
8 steps
python
from pathlib import Path from typing import Iterator
Filtering files with pathlib.glob
generators
filesystem
filtering
Intermediate
6 steps
rust
use once_cell::sync::Lazy; use regex::Regex; static NON_ALPHANUMERIC: Lazy<Regex> = Lazy::new(|| Regex::new(r"[^a-z0-9]+").unwrap());
Building URL slugs in Rust
string-processing
regex
transliteration
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/recursive-file-search-by-extension-in-rust-explained-rust-f548/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.