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!

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.

Create a Path

"./foo/bar.txt"

Path.file_stem

Some("bar")
true
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>.

Some("txt")
true

Path.exists

false
true

Path.is_file

false
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.

Ok("/workdir/archives/blog/misc/content/2021/05/rust-Path")
Components([RootDir, Normal("workdir"), Normal("archives"), Normal("blog"), Normal("misc"), Normal("content"), Normal("2021"), Normal("05"), Normal("rust-Path")])
"/"
"workdir"
"archives"
"blog"
"misc"
"content"
"2021"
"05"
"rust-Path"

Path.parent

Some("./foo")

Path.read_dir

"./rust-Path.ipynb"
"./test.txt"
"./.ipynb_checkpoints"