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
async function copyToClipboard(text) { if (navigator.clipboard && window.isSecureContext) { try { await navigator.clipboard.writeText(text);
Copying to the clipboard with a fallback
clipboard
progressive-enhancement
dom
Intermediate
8 steps
rust
use std::time::Duration; use tokio::time::sleep; #[derive(Debug)]
Async retry with exponential backoff in Rust
retry
exponential-backoff
async
Intermediate
8 steps
typescript
interface PollOptions<T> { intervalMs?: number; timeoutMs?: number; signal?: AbortSignal;
A cancellable polling helper in TypeScript
polling
async-await
abortsignal
Intermediate
9 steps
typescript
type Ok<T> = { ok: true; value: T }; type Err<E> = { ok: false; error: E }; export type Result<T, E> = Ok<T> | Err<E>;
A Result type for typed error handling
discriminated-union
error-handling
type-guards
Intermediate
8 steps
javascript
'use server' import { z } from 'zod' import { redirect } from 'next/navigation'
How a Next.js Server Action validates a form
server-actions
form-validation
zod
Intermediate
7 steps
ruby
module ConfigMerge module_function def deep_merge(base, override)
Recursively merging nested config hashes in Ruby
recursion
hash-merge
immutability
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.