Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Standard Library Modules

Rust PathBuf and Path types

Reference for std::path::Path and PathBuf: join, push and pop, file_name, extension, with_extension, components, strip_prefix, display and non-UTF-8 paths.

Path and PathBuf represent file system paths. Path is an unsized, borrowed view (like str), usually seen as &Path. PathBuf is the owned, growable version (like String). Most manipulation methods work purely on the text of the path and never touch the disk; only a few (exists, is_file, canonicalize, read_dir, metadata) ask the operating system.

Paths are not required to be valid UTF-8, because operating systems do not require it. Internally they are OsStrs, so converting to &str is fallible (to_str returns an Option), while display() and to_string_lossy() always give something printable.

Rust
use std::path::{Path, PathBuf};

let mut p = PathBuf::from("/home/ann");
p.push("notes.txt");

Try it

Rust Taking paths apart

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Building and changing paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl Path {
    pub fn new<S: AsRef<OsStr> + ?Sized>(s: &S) -> &Path;
    pub fn file_name(&self) -> Option<&OsStr>;
    pub fn file_stem(&self) -> Option<&OsStr>;
    pub fn extension(&self) -> Option<&OsStr>;
    pub fn parent(&self) -> Option<&Path>;
    pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf;
    pub fn with_extension<S: AsRef<OsStr>>(&self, ext: S) -> PathBuf;
    pub fn with_file_name<S: AsRef<OsStr>>(&self, name: S) -> PathBuf;
    pub fn strip_prefix<P: AsRef<Path>>(&self, base: P) -> Result<&Path, StripPrefixError>;
    pub fn starts_with<P: AsRef<Path>>(&self, base: P) -> bool;
    pub fn components(&self) -> Components<'_>;
    pub fn ancestors(&self) -> Ancestors<'_>;
    pub fn is_absolute(&self) -> bool;
    pub fn to_str(&self) -> Option<&str>;
    pub fn to_string_lossy(&self) -> Cow<'_, str>;
    pub fn display(&self) -> Display<'_>;
    pub fn exists(&self) -> bool;       // also is_file, is_dir, try_exists
}

impl PathBuf {
    pub fn new() -> PathBuf;
    pub fn push<P: AsRef<Path>>(&mut self, path: P);
    pub fn pop(&mut self) -> bool;
    pub fn set_extension<S: AsRef<OsStr>>(&mut self, ext: S) -> bool;
    pub fn set_file_name<S: AsRef<OsStr>>(&mut self, name: S);
    pub fn into_os_string(self) -> OsString;
}
Name Description
join / push Append a component. An absolute argument replaces the whole path.
with_* / set_* Return a changed copy, or change in place.
strip_prefix Ok(rest) if self starts with base on component boundaries, else an error.
display A wrapper that implements Display. Non-UTF-8 parts are replaced by U+FFFD.

Returns. file_name is None for paths that end in .. or are the root. extension is the part after the last dot, None if there is no dot or the name starts with the only dot. parent is None for the root or the empty path. pop and set_extension return false when there was nothing to remove.

Errors and panics. Methods that only look at text do not fail. The ones that touch the disk (exists, canonicalize, metadata, read_dir) return bool or io::Result; exists hides errors, so use try_exists if "cannot tell" matters.

Usage notes

  • Never join paths with format!("{}/{}") or +. join uses the platform's separator and handles empty parts and existing slashes.
  • Components, not strings. starts_with and ends_with compare whole components: "/home/annabel" does not start with "/home/ann".
  • .. is not resolved. Use canonicalize() (needs the path to exist, resolves symlinks) or normalize manually. Be careful with user-supplied paths: a joined .. can escape a base folder, which is a path traversal bug.
  • Take impl AsRef<Path> in function arguments so callers can pass &str, String, &Path or PathBuf. Return PathBuf when you build something new.
  • Windows. Paths can have prefixes (C:, \\server\share) and both \ and / are separators. The examples here show Linux behavior; use components() for portable logic.
  • Cheap vs costly. Path::new and most getters do not allocate; join, with_* and to_path_buf allocate a PathBuf.
  • Display in logs. Use {} with path.display(), or {:?} on the path itself, which quotes and escapes it.
  • Case. Comparisons are case-sensitive on every platform, even where the file system is not.