Finding files with glob patterns
As you may have noticed, using walkdir
to filter files based on their name can be a bit clunky at times. Luckily, you can greatly simplify this by using the glob
crate, which brings you its titular patterns, known from Unix, right into Rust.
How to do it...
Follow these steps:
Open the
Cargo.toml
file that was generated earlier for you.- Under
[dependencies]
, add the following line:
glob = "0.2.11"
- If you want, you can go to glob's crates.io page (https://crates.io/crates/glob) to check for the newest version and use that one instead.
In the
bin
folder, create a file calledglob.rs
.Add the following code and run it with
cargo run --bin glob
:
1 extern crate glob; 2 use glob::{glob, glob_with, MatchOptions}; 3 4 fn main() { 5 println!("All all Rust files in all subdirectories:"); 6 for entry in glob("**/*.rs").expect("Failed to read glob pattern") { 7 match entry { 8 Ok(path) => println!("{:?}", path.display()), 9 ...