Path and
PathBuf use
OsStr and OsString respectively to handle operating system paths to
file systems. Path is thus a slice on a file system path, and
PathBuf a path stored on the heap.
See Table 1 and Table 2 for lists of the most useful methods for these both types.
Table 1:Some methods of Path
Method | Description |
|---|---|
| Returns an iterator over all parent paths starting from this path. |
| Returns the underlying |
| Returns the canonical & absolute form of the path with symbolic links resolved. |
| Returns an iterator over all individual components of the path. |
| Returns an object that can be used to safely print the path. |
| Tests if |
| Returns |
| Returns the extension without the dot. |
| Returns the final component, including any extension. |
| Returns the start of the file name up to the eventual dot character. If the file name starts with a dot, it does not account as a termination. |
| Returns the final component, without the eventual extension. |
| Returns |
| Returns |
| Returns |
| Returns |
| Returns |
| Returns |
| Returns |
| Returns an iterator over the components of this path, viewed as
|
| Returns a |
| Returns the Metadata (size, file type, ...) of this path. |
| Returns the |
| Returns an iterator over the entries of a directory. |
| Returns the |
| Tests if |
| Returns the path without the prefix |
| Converts this path to a |
| Converts this path into a string slice. |
| Converts this path into a string with non-UTF-8 sequences
replaced with |
| Create a |
| Create a |
The Path struct resides inside the std::path module. We declare it
using the use keyword:
use std::path::Path;The new() method can be used to create a new Path object from a
string slice:
let file = Path::new("data/measures.tsv");Couldn't automatically determine type of variable `file`.
Please give it an explicit type.We can extract the file name from the path as following:
file.file_name()The extension:
file.extension()The name without the extension:
file.file_stem()We can change the extension:
file.with_extension("txt")Table 2:Some methods of PathBuf
Method | Description |
|---|---|
| Appends an extension to this path. |
| Returns the underlying |
| Empty this path. |
| Creates a new empty path. |
| Truncates this path to its parent. |
| Appends p to this path. |
| Replaces the current extension with |
| Replaces the current file name with |
The PathBuf struct resides inside the std::path module. We declare
it using the use keyword:
use std::path::PathBuf;The new() method can be used to create a new empty PathBuf object:
let mut file2 = PathBuf::new();We can then add some path to it:
file2.push("README.md");
file2We may also transform a Path instance into a new PathBuf instance:
file.to_path_buf()