Answer#
Windows separates path parts with \ and macOS with /. Instead of gluing strings together (format!("{dir}/{name}")), use PathBuf, which knows the rules of the system the program is compiled for.
use std::path::{Path, PathBuf};
fn main() {
let mut p = PathBuf::from("projects");
p.push("demo");
p.push("notes.txt");
println!("{}", p.display()); // the separator is the running system's own
println!("file_name: {:?}", p.file_name().unwrap());
println!("extension: {:?}", p.extension().unwrap());
println!("parent: {:?}", p.parent().unwrap());
println!("with_extension: {}", p.with_extension("md").display());
// join() with an absolute path REPLACES what came before it:
let base = Path::new("data");
println!("{}", base.join("a.txt").display());
println!("{}", base.join("C:\\other\\a.txt").display());
// Components are the portable way to walk a path:
for c in Path::new("a/b/../c.txt").components() {
print!("{c:?} ");
}
println!();
}projects\demo\notes.txt
file_name: "notes.txt"
extension: "txt"
parent: "projects\\demo"
with_extension: projects\demo\notes.md
data\a.txt
C:\other\a.txt
Normal("a") Normal("b") ParentDir Normal("c.txt") What to learn from the output:
- The separator follows the system. The same source prints
projects/demo/notes.txtwhen built for macOS. joinandpushwith an absolute path discard the left side. Ifnamecomes from outside (a file, the network), joining it onto a base folder can escape the folder. Reject any such name that is absolute or contains..before joining.a/b/../c.txtis parsed withParentDir. Paths are not simplified for you;components()shows the structure. Windows accepts/as well as\in paths you give it, soPath::new("a/b")works on both.- Use the accessors.
file_name,extension,parentandwith_extensionhandle edge cases (a name with several dots, a trailing separator) that string splitting gets wrong.
Common mistakes#
- Hard-coding
\\or/in a string path. - Converting to
Stringwithto_str().unwrap()for every operation. Keep values asPath/PathBufuntil you show them to a person; see the thread on non-UTF-8 paths. - Comparing paths as strings.
C:\Aandc:\aare the same folder on Windows.
Related questions#
What does display() do?#
It gives a value that prints the path for humans. It is for output only; do not parse its text.
Sources#
- std::path: https://doc.rust-lang.org/std/path/index.html (read 2026-12-05)
- std::path::Path::join: https://doc.rust-lang.org/std/path/struct.Path.html#method.join (read 2026-12-05)