bhylu.com

Advertisements

Rust Paths and PathBuf

Build a path without treating it as a permission decision.

How it works

Path and PathBuf represent borrowed and owned filesystem paths. They avoid manual separator concatenation but do not validate whether a request should access a resource. A joined absolute or parent-traversal component can change the intended destination, so map untrusted identifiers to trusted paths or use a carefully reviewed resolver. Text encoding and path representation also differ across operating systems.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

paths.rs

fn main() {
    use std::path::PathBuf;
    let path = PathBuf::from("seed-data").join("north.txt");
    assert_eq!(path.file_name().and_then(|x| x.to_str()), Some("north.txt"));
    assert!(!path.is_absolute());
    println!("Relative path built with filename north.txt");
}

Expected result

Relative path built with filename north.txt

The filename component is fixed trusted text, and the example performs no file access. It checks structural properties instead of comparing platform-specific separator displays. A server accepting a download ID must still check the authenticated user’s permission and keep the storage boundary independent from convenient path-building syntax.

Primary technical reference: Rust documentation.