Path
The Path struct represents file paths in the underlying filesystem.
There are two flavors of Path:
posix::Path, for UNIX-like systems- and
windows::Path, for Windows.
The prelude exports the appropriate platform-specific
Pathvariant.
-
A
Pathcan be created from anOsStr, and provides several methods to get information from the file/directory the path points to. -
A
Pathis immutable. -
The owned version of
PathisPathBuf.
The relation between
PathandPathBufis similar to that ofstrandString:
- a
PathBufcan be mutated in-place, - and can be dereferenced to a
Path.
Note that a
Pathis not internally represented as an UTF-8 string, but instead is stored as anOsString.
- Therefore, converting a
Pathto a&stris not free and may fail (anOptionis returned). - However, a
Pathcan be freely converted to anOsStringor&OsStrusinginto_os_stringandas_os_str, respectively.
Path Usage Examples
use std::path::Path; fn main() { // Create a `Path` from an `&'static str` let path = Path::new("."); // The `display` method returns a `Display`able structure let _display = path.display(); // `join` merges a path with a byte container using the OS specific // separator, and returns a `PathBuf` let mut new_path = path.join("a").join("b"); // `push` extends the `PathBuf` with a `&Path` new_path.push("c"); new_path.push("myfile.tar.gz"); // `set_file_name` updates the file name of the `PathBuf` new_path.set_file_name("package.tgz"); // Convert the `PathBuf` into a string slice match new_path.to_str() { None => panic!("new path is not a valid UTF-8 sequence"), Some(s) => println!("new path is {}", s), } }
- Create a
Pathfrom an&'static str - The
displaymethod returns aDisplayable structure joinmerges a path with a byte container using the OS specific separator, and returns aPathBufpushextends thePathBufwith a&Pathset_file_nameupdates the file name of thePathBuf
Be sure to check at other Path methods (posix::Path or windows::Path) and
the Metadata struct.