Struct PathBuf
struct PathBuf { ... }
An owned, mutable path (akin to String).
This type provides methods like push and set_extension that mutate
the path in place. It also implements Deref to Path, meaning that
all methods on Path slices are available on PathBuf values as well.
More details about the overall approach can be found in the module documentation.
Examples
You can use push to build up a PathBuf from
components:
use PathBuf;
let mut path = new;
path.push;
path.push;
path.push;
path.set_extension;
However, push is best used for dynamic situations. This is a better way
to do this when you know all of the components ahead of time:
use PathBuf;
let path: PathBuf = .iter.collect;
We can still do better than this! Since these are all strings, we can use
From::from:
use PathBuf;
let path = from;
Which method works best depends on what kind of situation you're in.
Note that PathBuf does not always sanitize arguments, for example
push allows paths built from strings which include separators:
use PathBuf;
let mut path = new;
path.push;
path.push;
path.push;
path.push;
The behavior of PathBuf may be changed to a panic on such inputs
in the future. Extend::extend should be used to add multi-part paths.
Implementations
impl PathBuf
const fn new() -> PathBufAllocates an empty
PathBuf.Examples
use PathBuf; let path = new;fn with_capacity(capacity: usize) -> PathBufCreates a new
PathBufwith a given capacity used to create the internalOsString. Seewith_capacitydefined onOsString.Examples
use PathBuf; let mut path = with_capacity; let capacity = path.capacity; // This push is done without reallocating path.push; assert_eq!;fn as_path(self: &Self) -> &PathCoerces to a
Pathslice.Examples
use ; let p = from; assert_eq!;fn leak<'a>(self: Self) -> &'a mut PathConsumes and leaks the
PathBuf, returning a mutable reference to the contents,&'a mut Path.The caller has free choice over the returned lifetime, including 'static. Indeed, this function is ideally used for data that lives for the remainder of the program's life, as dropping the returned reference will cause a memory leak.
It does not reallocate or shrink the
PathBuf, so the leaked allocation may include unused capacity that is not part of the returned slice. If you want to discard excess capacity, callinto_boxed_path, and thenBox::leakinstead. However, keep in mind that trimming the capacity may result in a reallocation and copy.fn push<P: AsRef<Path>>(self: &mut Self, path: P)Extends
selfwithpath.If
pathis absolute, it replaces the current path.On Windows:
- if
pathhas a root but no prefix (e.g.,\windows), it replaces everything except for the prefix (if any) ofself. - if
pathhas a prefix but no root, it replacesself. - if
selfhas a verbatim prefix (e.g.\\?\C:\windows) andpathis not empty, the new path is normalized: all references to.and..are removed.
Consider using
Path::joinif you need a newPathBufinstead of using this function on a clonedPathBuf.Examples
Pushing a relative path extends the existing path:
use PathBuf; let mut path = from; path.push; assert_eq!;Pushing an absolute path replaces the existing path:
use PathBuf; let mut path = from; path.push; assert_eq!;- if
fn pop(self: &mut Self) -> boolTruncates
selftoself.parent.Returns
falseand does nothing ifself.parentisNone. Otherwise, returnstrue.Examples
use ; let mut p = from; p.pop; assert_eq!; p.pop; assert_eq!;fn set_trailing_sep(self: &mut Self, trailing_sep: bool)Sets whether the path has a trailing separator.
The value returned by
has_trailing_sepwill be equivalent to the provided value if possible.Examples
use PathBuf; let mut p = from; assert!; p.set_trailing_sep; assert!; p.set_trailing_sep; assert!; p.set_trailing_sep; assert!; p = from; assert!; p.set_trailing_sep; assert!;fn push_trailing_sep(self: &mut Self)Adds a trailing separator to the path.
This acts similarly to
Path::with_trailing_sep, but mutates the underlyingPathBuf.Examples
use OsStr; use PathBuf; let mut p = from; assert!; p.push_trailing_sep; assert!; p.push_trailing_sep; assert!; p = from; p.push_trailing_sep; assert_eq!;fn pop_trailing_sep(self: &mut Self)Removes a trailing separator from the path, if possible.
This acts similarly to
Path::trim_trailing_sep, but mutates the underlyingPathBuf.Examples
use OsStr; use PathBuf; let mut p = from; assert!; assert_eq!; p.pop_trailing_sep; assert!; assert_eq!; p.pop_trailing_sep; assert!; assert_eq!; p = from; assert!; p.pop_trailing_sep; assert!;fn set_file_name<S: AsRef<OsStr>>(self: &mut Self, file_name: S)Updates
self.file_nametofile_name.If
self.file_namewasNone, this is equivalent to pushingfile_name.Otherwise it is equivalent to calling
popand then pushingfile_name. The new path will be a sibling of the original path. (That is, it will have the same parent.)The argument is not sanitized, so can include separators. This behavior may be changed to a panic in the future.
Examples
use PathBuf; let mut buf = from; assert!; buf.set_file_name; assert!; assert!; buf.set_file_name; assert!; buf.set_file_name; assert!; buf.set_file_name; assert!; buf.set_file_name; assert!;fn set_extension<S: AsRef<OsStr>>(self: &mut Self, extension: S) -> boolUpdates
self.extensiontoSome(extension)or toNoneifextensionis empty.Returns
falseand does nothing ifself.file_nameisNone, returnstrueand updates the extension otherwise.If
self.extensionisNone, the extension is added; otherwise it is replaced.If
extensionis the empty string,self.extensionwill beNoneafterwards, notSome("").Panics
Panics if the passed extension contains a path separator (see
is_separator).Caveats
The new
extensionmay contain dots and will be used in its entirety, but only the part after the final dot will be reflected inself.extension.If the file stem contains internal dots and
extensionis empty, part of the old file stem will be considered the newself.extension.See the examples below.
Examples
use ; let mut p = from; p.set_extension; assert_eq!; p.set_extension; assert_eq!; p.set_extension; assert_eq!; p.set_extension; assert_eq!; p.set_extension; assert_eq!; p.set_extension; assert_eq!;fn add_extension<S: AsRef<OsStr>>(self: &mut Self, extension: S) -> boolAppend
self.extensionwithextension.Returns
falseand does nothing ifself.file_nameisNone, returnstrueand updates the extension otherwise.Panics
Panics if the passed extension contains a path separator (see
is_separator).Caveats
The appended
extensionmay contain dots and will be used in its entirety, but only the part after the final dot will be reflected inself.extension.See the examples below.
Examples
use ; let mut p = from; p.add_extension; assert_eq!; p.add_extension; assert_eq!; p.set_extension; assert_eq!; p.set_extension; assert_eq!; p.add_extension; assert_eq!;fn as_mut_os_string(self: &mut Self) -> &mut OsStringYields a mutable reference to the underlying
OsStringinstance.Examples
use ; let mut path = from; path.push; assert_eq!; // OsString's `push` does not add a separator. path.as_mut_os_string.push; assert_eq!;fn into_os_string(self: Self) -> OsStringConsumes the
PathBuf, yielding its internalOsStringstorage.Examples
use PathBuf; let p = from; let os_str = p.into_os_string;fn into_boxed_path(self: Self) -> Box<Path>fn capacity(self: &Self) -> usizefn clear(self: &mut Self)fn reserve(self: &mut Self, additional: usize)fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Invokes
try_reserveon the underlying instance ofOsString.fn reserve_exact(self: &mut Self, additional: usize)Invokes
reserve_exacton the underlying instance ofOsString.fn try_reserve_exact(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Invokes
try_reserve_exacton the underlying instance ofOsString.fn shrink_to_fit(self: &mut Self)Invokes
shrink_to_fiton the underlying instance ofOsString.fn shrink_to(self: &mut Self, min_capacity: usize)
impl AsRef for PathBuf
fn as_ref(self: &Self) -> &Path
impl AsRef for PathBuf
fn as_ref(self: &Self) -> &OsStr
impl Borrow for PathBuf
fn borrow(self: &Self) -> &Path
impl Clone for PathBuf
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)Clones the contents of
sourceintoself.This method is preferred over simply assigning
source.clone()toself, as it avoids reallocation if possible.
impl Debug for PathBuf
fn fmt(self: &Self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result
impl Default for PathBuf
fn default() -> Self
impl Deref for PathBuf
fn deref(self: &Self) -> &Path
impl DerefMut for PathBuf
fn deref_mut(self: &mut Self) -> &mut Path
impl Eq for PathBuf
impl Freeze for PathBuf
impl From for PathBuf
fn from(boxed: Box<Path>) -> PathBufConverts a
[Box]<[Path]>into aPathBuf.This conversion does not allocate or copy memory.
impl From for PathBuf
impl From for PathBuf
impl FromStr for PathBuf
fn from_str(s: &str) -> Result<Self, <Self as >::Err>
impl Hash for PathBuf
fn hash<H: Hasher>(self: &Self, h: &mut H)
impl Ord for PathBuf
fn cmp(self: &Self, other: &PathBuf) -> cmp::Ordering
impl PartialEq for PathBuf
fn eq(self: &Self, other: &String) -> bool
impl PartialEq for PathBuf
fn eq(self: &Self, other: &Path) -> bool
impl PartialEq for PathBuf
fn eq(self: &Self, other: &PathBuf) -> bool
impl PartialEq for PathBuf
fn eq(self: &Self, other: &OsString) -> bool
impl PartialEq for PathBuf
fn eq(self: &Self, other: &OsStr) -> bool
impl PartialEq for PathBuf
fn eq(self: &Self, other: &str) -> bool
impl PartialOrd for PathBuf
fn partial_cmp(self: &Self, other: &PathBuf) -> Option<cmp::Ordering>
impl PartialOrd for PathBuf
fn partial_cmp(self: &Self, other: &Path) -> Option<cmp::Ordering>
impl PartialOrd for PathBuf
fn partial_cmp(self: &Self, other: &OsString) -> Option<cmp::Ordering>
impl PartialOrd for PathBuf
fn partial_cmp(self: &Self, other: &OsStr) -> Option<cmp::Ordering>
impl RefUnwindSafe for PathBuf
impl Send for PathBuf
impl Sync for PathBuf
impl Unpin for PathBuf
impl UnwindSafe for PathBuf
impl<'a> From for PathBuf
fn from(p: Cow<'a, Path>) -> SelfConverts a clone-on-write pointer to an owned path.
Converting from a
Cow::Owneddoes not clone or allocate.
impl<'a> PartialEq for PathBuf
fn eq(self: &Self, other: &&'a OsStr) -> bool
impl<'a> PartialEq for PathBuf
fn eq(self: &Self, other: &Cow<'a, OsStr>) -> bool
impl<'a> PartialEq for PathBuf
fn eq(self: &Self, other: &&'a Path) -> bool
impl<'a> PartialEq for PathBuf
fn eq(self: &Self, other: &Cow<'a, Path>) -> bool
impl<'a> PartialOrd for PathBuf
fn partial_cmp(self: &Self, other: &&'a OsStr) -> Option<cmp::Ordering>
impl<'a> PartialOrd for PathBuf
fn partial_cmp(self: &Self, other: &Cow<'a, OsStr>) -> Option<cmp::Ordering>
impl<'a> PartialOrd for PathBuf
fn partial_cmp(self: &Self, other: &&'a Path) -> Option<cmp::Ordering>
impl<'a> PartialOrd for PathBuf
fn partial_cmp(self: &Self, other: &Cow<'a, Path>) -> Option<cmp::Ordering>
impl<P, T> Receiver for PathBuf
impl<P: AsRef<Path>> Extend for PathBuf
fn extend<I: IntoIterator<Item = P>>(self: &mut Self, iter: I)Extends
selfwithPathelements fromiter.This uses
pushto add each element, so can be used to adjoin multiple path components.Examples
# use PathBuf; let mut path = from; path.extend; assert_eq!;See documentation for
pushfor more details on how the path is constructed.fn extend_one(self: &mut Self, p: P)
impl<P: AsRef<Path>> FromIterator for PathBuf
fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> PathBufCreates a new
PathBuffrom thePathelements of an iterator.This uses
pushto add each element, so can be used to adjoin multiple path components.Examples
# use PathBuf; let path = from_iter; assert_eq!;See documentation for
pushfor more details on how the path is constructed.
impl<T> Any for PathBuf
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for PathBuf
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for PathBuf
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for PathBuf
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for PathBuf
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for PathBuf
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for PathBuf
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for PathBuf
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for PathBuf
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>