Path and PathBuf

Path and PathBuf join, push, parent, and components, with separators as measured on macOS rather than invented Windows paths.

テーマページの本文は現在英語です。

Path is a standard-library unsized type for a file-system path, usually seen as &Path. PathBuf is the owned, growable path and dereferences to Path. Both live in std::path. They are not a third-party crate.

The examples on this page were run with rustc 1.90.0 on macOS aarch64 (darwin), where the separator is a slash. They do not invent Windows backslash output. Official documentation says that on Windows a path is absolute if it has a prefix and starts with the root, so c:\windows is absolute while c:temp and \temp are not. That Windows behavior is not measured here. On this host, Path::new(r"C:\tmp\x").is_absolute() is false.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
Path::new, Path::join, Path::parent, Path::file_name, Path::extension, Path::file_stem, Path::to_str, Path::displayBuild a path with join, then inspect the parent and the final file name. An absolute second argument replaces the path.
PathBuf::push, PathBuf::pop, Path::is_absolute, Path::componentsGrow or shrink an owned path, test whether it is absolute on this OS, and walk its components.

join, parent, and file names

join adjoins a path onto self and returns a new PathBuf. If the argument is absolute, it replaces the current path: on this Unix host, Path::new("home").join("/etc/passwd") is /etc/passwd, not home/etc/passwd. parent returns the path without the final component. file_name is the final component, extension is the suffix after the final dot of that component, and file_stem is the part before that last extension. These name helpers return Option<&OsStr>; the example converts with to_str, which succeeds for valid Unicode and returns None when the path is not valid UTF-8.

Path::new, Path::join, Path::parent, Path::file_name, Path::extension, Path::file_stem, Path::to_str, Path::display

pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path
pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf
pub fn parent(&self) -> Option<&Path>
pub fn file_name(&self) -> Option<&OsStr>
pub fn extension(&self) -> Option<&OsStr>
pub fn file_stem(&self) -> Option<&OsStr>
pub fn to_str(&self) -> Option<&str>
pub fn display(&self) -> Display<'_>

Build a path with join, then inspect the parent and the final file name. An absolute second argument replaces the path.

ParameterDescription
s / pathnew wraps a string or OsStr as a Path. join takes any AsRef<Path> and returns an owned PathBuf without modifying self.

Returns: join returns a PathBuf. parent returns Option<&Path>. file_name, extension, and file_stem return Option<&OsStr>. to_str returns Option<&str>. display returns a type that implements Display for printing a path.

  • These outputs were measured on macOS aarch64. Do not treat the slash-separated results as Windows output.
  • to_string_lossy returns Cow<str> and replaces invalid sequences, which is useful when you must print a path that may not be UTF-8. This example only uses valid UTF-8.
  • Official documentation includes Path::new("/etc").join("/bin/sh") == PathBuf::from("/bin/sh"). The replacement rule was also measured below with join("/etc/passwd").
rust
use std::path::Path;

fn main() {
    println!("join-rel {}", Path::new("home/ada").join("src.rs").display());
    println!("join-abs-elem {}", Path::new("home").join("/etc/passwd").display());
    println!("join-abs-base {}", Path::new("/etc").join("passwd").display());
    let p = Path::new("home/ada/src.rs");
    println!(
        "parts parent={:?} file_name={:?} ext={:?} stem={:?}",
        p.parent().map(|x| x.display().to_string()),
        p.file_name().and_then(|x| x.to_str()),
        p.extension().and_then(|x| x.to_str()),
        p.file_stem().and_then(|x| x.to_str())
    );
    println!("to_str={:?} display={}", p.to_str(), p.display());
}

Expected output

join-rel home/ada/src.rs
join-abs-elem /etc/passwd
join-abs-base /etc/passwd
parts parent=Some("home/ada") file_name=Some("src.rs") ext=Some("rs") stem=Some("src")
to_str=Some("home/ada/src.rs") display=home/ada/src.rs

Official documentation →

PathBuf push, is_absolute, and components

PathBuf::push adjoins a path in place, using the same replacement rule as join when the argument is absolute. pop removes the last component and returns whether anything was removed. is_absolute reports whether the path is independent of the current directory. On Unix this is equivalent to having a root. On this macOS host, "/tmp/x" is absolute and both "tmp/x" and the Windows-looking string r"C:\tmp\x" are not.

components walks the path as RootDir, CurDir, ParentDir, Prefix, or Normal. The Debug output below is from this host for "/tmp/foo.txt". Prefix appears on Windows and is not demonstrated here. A string can be passed where AsRef<Path> is required, including to Path::new and to functions in std::fs.

PathBuf::push, PathBuf::pop, Path::is_absolute, Path::components

pub fn push<P: AsRef<Path>>(&mut self, path: P)
pub fn pop(&mut self) -> bool
pub fn is_absolute(&self) -> bool
pub fn components(&self) -> Components<'_>

Grow or shrink an owned path, test whether it is absolute on this OS, and walk its components.

ParameterDescription
pathpush takes any AsRef<Path>. An absolute argument replaces the current value, as with join.

Returns: push has no return value. pop returns true if a component was removed. is_absolute returns a bool. components returns an iterator of Component values.

  • On this host is_absolute(r"C:\tmp\x") is false. A Windows measurement is not shown, and this page does not claim that Windows behavior was verified locally.
  • as_path borrows a PathBuf as &Path without moving it.
rust
use std::path::{Path, PathBuf};

fn main() {
    println!(
        "is_abs {} {} {}",
        Path::new("/tmp/x").is_absolute(),
        Path::new("tmp/x").is_absolute(),
        Path::new(r"C:\tmp\x").is_absolute()
    );
    let mut buf = PathBuf::from("home");
    buf.push("ada");
    buf.push("src.rs");
    println!("pushed {}", buf.display());
    let popped = buf.pop();
    println!("popped {popped} {}", buf.display());
    println!("components");
    for c in Path::new("/tmp/foo.txt").components() {
        println!("  {c:?}");
    }
    println!("as_ref {}", AsRef::<Path>::as_ref("home/ada").display());
}

Expected output

is_abs true false false
pushed home/ada/src.rs
popped true home/ada
components
  RootDir
  Normal("tmp")
  Normal("foo.txt")
as_ref home/ada

Official documentation →