Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on the Glob Crate in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

The Rust crate glob behaves similarly to the Python library glob.

In [2]:
:sccache 1
:dep glob = "0.3.0"
Out[2]:
sccache: true
In [15]:
use std::fs::DirEntry;
use std::path::PathBuf;
use glob::glob;
In [4]:
for entry in glob("./**/*").unwrap() {
    if let Ok(entry) = entry {
        println!("{:?}", entry);
    }
}
".ipynb_checkpoints"
".ipynb_checkpoints/hands-on-the-glob-crate-in-rust-checkpoint.ipynb"
"hands-on-the-glob-crate-in-rust.ipynb"
"test"
"test/.ipynb_checkpoints"
"test/.ipynb_checkpoints/test-checkpoint.txt"
"test/test.txt"
"test/test2"
"test/test2/.ipynb_checkpoints"
"test/test2/.ipynb_checkpoints/test2-checkpoint.txt"
"test/test2/test2.txt"
Out[4]:
()

Collect valid paths matching a pattern into a vector.

In [25]:
let paths: Vec<PathBuf> = glob("./**/*").unwrap().flatten().collect(); 
paths
Out[25]:
[".ipynb_checkpoints", ".ipynb_checkpoints/hands-on-the-glob-crate-in-rust-checkpoint.ipynb", "hands-on-the-glob-crate-in-rust.ipynb", "test", "test/.ipynb_checkpoints", "test/.ipynb_checkpoints/test-checkpoint.txt", "test/test.txt", "test/test2", "test/test2/.ipynb_checkpoints", "test/test2/.ipynb_checkpoints/test2-checkpoint.txt", "test/test2/test2.txt"]
In [26]:
paths.len()
Out[26]:
11
In [ ]:

Comments