Ben Chuanlong Du's Blog

It is never too late to learn.

Path in Rust

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

In [ ]:
: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.

  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.

In [3]:
use std::path::Path;
use std::ffi::OsStr;

Create a Path

In [4]:
let path = Path::new("./foo/bar.txt");
path
Out[4]:
"./foo/bar.txt"

Path.file_stem

In [6]:
path.file_stem()
Out[6]:
Some("bar")
In [7]:
path.file_stem() == Some(OsStr::new("bar"))
Out[7]:
true
In [8]:
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>.

In [15]:
let path = Path::new("./foo/bar.txt");
path.extension()
Out[15]:
Some("txt")
In [17]:
let path = Path::new("./foo/bar.txt");
path.extension() == Some(OsStr::new("txt"))
Out[17]:
true

Path.exists

In [13]:
path.exists()
Out[13]:
false
In [15]:
Path::new("test.txt").exists()
Out[15]:
true

Path.is_file

In [18]:
path.is_file()
Out[18]:
false
In [16]:
Path::new("test.txt").is_file()
Out[16]:
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.

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

Path.parent

In [5]:
path.parent()
Out[5]:
Some("./foo")

Path.read_dir

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

Comments