Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Standard Library Modules

The std::path module

Reference for std::path: Path and PathBuf, join, parent, file_name, extension, file_stem, with_extension, components, strip_prefix and platform differences.

std::path models filesystem paths. Path is an unsized, borrowed view (like str) and PathBuf is its owned, growable counterpart (like String). Both wrap an OsStr, so a path may contain bytes that are not valid UTF-8, which is legal on Unix and on Windows.

Path methods work on the text of the path: they split, join and compare components without touching the disk. Methods that ask the filesystem (exists, is_file, canonicalize) are also on Path, but they are thin wrappers over std::fs.

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

let p = Path::new("/srv/app/config.toml");
let mut dir = PathBuf::from("/srv");
dir.push("app");

Try it

Rust Taking a path 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 paths with PathBuf

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
pub struct Path { /* unsized */ }
pub struct PathBuf { /* owned */ }
Method (on Path) Returns Description
Path::new(s) &Path Borrow any AsRef<OsStr> as a path; no allocation.
join(p) PathBuf Append; an absolute p replaces the whole path.
parent() Option<&Path> Path without its last component; None for a root or empty path.
file_name() Option<&OsStr> Last component, or None if it ends in ...
file_stem(), extension() Option<&OsStr> Name before and after the last dot (.hidden has no extension).
with_extension(e), with_file_name(n) PathBuf Copy with one part replaced.
components(), iter(), ancestors() iterators Walk parts or parents; components normalizes . and repeated separators.
strip_prefix(base) Result<&Path, StripPrefixError> Remove a leading path.
starts_with, ends_with bool Whole-component comparison, not string comparison.
is_absolute(), is_relative(), has_root() bool Platform-aware tests.
to_str(), to_string_lossy(), display() Option<&str>, Cow<str>, Display Convert to text; display is for printing.
exists(), is_file(), is_dir(), metadata(), read_dir(), canonicalize() various Filesystem queries.

PathBuf adds push, pop, set_extension, set_file_name, as_path, into_os_string and PathBuf::with_capacity.

Errors and edge cases: strip_prefix fails when the prefix is not a prefix; to_str returns None for non-UTF-8 paths; pop returns false on an empty path.

Usage notes

  • Never build paths by concatenating strings with /. Use join and push; they use the right separator and avoid doubled slashes.
  • Functions should take impl AsRef<Path> so callers can pass &str, String, &Path or PathBuf.
  • Path does not implement Display; call .display() for messages. It may replace invalid sequences, so do not use it to round-trip.
  • components() collapses a//b and ./a, but keeps .. because resolving it needs the filesystem (symlinks). Use fs::canonicalize for that, with the file present.
  • On Windows, prefixes (C:, \\?\) and both \ and / separators are understood; on Unix only / separates. The examples here show Unix behavior.
  • Path equality compares components, so "a/b" equals "a//b", but case is significant on Unix.
  • Join untrusted names carefully: an absolute or ..-laden name can escape the base directory (path traversal).