Path Components Match Segment Kinds

Walk Path::components and match each Component variant to classify prefixes, roots, parent hops, and normal segments.

RustSecurity Boundaries

Code

rustsnippet
23 lines
use std::path::{Component, Path};

fn describe(path: &str) {
    let mut parts: Vec<String> = Vec::new();
    // each segment of the path surfaces as one Component variant
    for segment in Path::new(path).components() {
        match segment {
            Component::Prefix(_) => parts.push("prefix".into()),
            Component::RootDir => parts.push("root".into()),
            Component::CurDir => parts.push("self".into()),
            Component::ParentDir => parts.push("parent".into()),
            Component::Normal(name) => parts.push(format!("name={}", name.to_string_lossy())),
        }
    }
    println!("{path} -> {}", parts.join(", "));
}

fn main() {
    describe("./tmp/../logs/app.log");
    describe("/etc/hostname");
    describe("uploads/avatar.png");
    describe("uploads/../../etc/shadow");
}

Inside the snippet

The working surface is the functions describe and main — everything else is wiring.

for segment in Path::new(path).components() is the loop that carries the per-item work. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Using it

The entry-point signature is fn describe(path: &str)

main sequences describe; executing the file runs that flow once.

Interactive Tools for This Topic

FAQ

How do you run Path Components Match Segment Kinds?
Run the file on its own; every call resolves against the standard surface it already imports.