Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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

:timing
:sccache 1

Tips and Traps

  1. This is an unsized type, meaning that it must always be used behind a pointer like & or Box.

    For an owned version of this type, see [PathBuf](https://doc.rust-lang.org/nightly/std/path/struct.PathBuf.html).

  2. Methods of std::path::Path return object of the type std::ffi::OsStr rather than std::String or &sstr.

  3. The Rust crate normpath provides more reliable path manipulation.

use std::path::Path;
use std::ffi::OsStr;

Create a Path

let path = Path::new("./foo/bar.txt");
path
"./foo/bar.txt"

Path.file_stem

path.file_stem()
Some("bar")
path.file_stem() == Some(OsStr::new("bar"))
true
path.file_stem() == Some(String::from("bar"))
path.file_stem() == Some(String::from("bar"))
                         ^^^^^^^^^^^^^^^^^^^ expected `&OsStr`, found struct `String`
mismatched types

path.extension(&self) -> Option<&OsStr>

Extracts the extension of self.file_name, if possible. Notice that this method returns Option<&OsStr> instead of Option<&str>.

let path = Path::new("./foo/bar.txt");
path.extension()
Some("txt")
let path = Path::new("./foo/bar.txt");
path.extension() == Some(OsStr::new("txt"))
true

Path.exists

path.exists()
false
Path::new("test.txt").exists()
true

Path.is_file

path.is_file()
false
Path::new("test.txt").is_file()
true

Path.iter

Produces an iterator over the path’s components viewed as OsStr slices.

Note: This function does not get the content of a directory! To get the content of a directory, use the function Path.read_dir.

Path::new(".").canonicalize()
Ok("/workdir/archives/blog/misc/content/2021/05/rust-Path")
Path::new(".").canonicalize().unwrap().components()
Components([RootDir, Normal("workdir"), Normal("archives"), Normal("blog"), Normal("misc"), Normal("content"), Normal("2021"), Normal("05"), Normal("rust-Path")])
Path::new(".").canonicalize().unwrap().iter().for_each(|comp| {
    println!("{:?}", comp);
});
"/"
"workdir"
"archives"
"blog"
"misc"
"content"
"2021"
"05"
"rust-Path"

Path.parent

path.parent()
Some("./foo")

Path.read_dir

Path::new(".").read_dir().unwrap().for_each(|entry| {
    if let Ok(entry) = entry {
        println!("{:?}", entry.path());
    }
});
"./rust-Path.ipynb"
"./test.txt"
"./.ipynb_checkpoints"