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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 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.