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.
| Parameter | Description |
|---|---|
s / path | new 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").
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