Skip to content

Commit 461d147

Browse files
committed
Document Path::parent behavior around relative paths
A relative path with just one component will return `Some("")` as its parent, which wasn't clear to me from the documentation. The parent of `""` is `None`, which was missing from the documentation as well.
1 parent 742d3f0 commit 461d147

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

library/std/src/path.rs

+12-1
Original file line numberDiff line numberDiff line change
@@ -2142,7 +2142,10 @@ impl Path {
21422142

21432143
/// Returns the `Path` without its final component, if there is one.
21442144
///
2145-
/// Returns [`None`] if the path terminates in a root or prefix.
2145+
/// This means it returns `Some("")` for relative paths with one component.
2146+
///
2147+
/// Returns [`None`] if the path terminates in a root or prefix, or if it's
2148+
/// the empty string.
21462149
///
21472150
/// # Examples
21482151
///
@@ -2156,6 +2159,14 @@ impl Path {
21562159
/// let grand_parent = parent.parent().unwrap();
21572160
/// assert_eq!(grand_parent, Path::new("/"));
21582161
/// assert_eq!(grand_parent.parent(), None);
2162+
///
2163+
/// let relative_path = Path::new("foo/bar");
2164+
/// let parent = relative_path.parent();
2165+
/// assert_eq!(parent, Some(Path::new("foo")));
2166+
/// let grand_parent = parent.and_then(Path::parent);
2167+
/// assert_eq!(grand_parent, Some(Path::new("")));
2168+
/// let great_grand_parent = grand_parent.and_then(Path::parent);
2169+
/// assert_eq!(great_grand_parent, None);
21592170
/// ```
21602171
#[stable(feature = "rust1", since = "1.0.0")]
21612172
#[doc(alias = "dirname")]

0 commit comments

Comments
 (0)