Skip to content

Commit 23382e6

Browse files
committed
Add more ways to create a PathBuf to docs
The best way to do this wasn't in the documentation, and the ways that were there needed some extra text to elaborate. Fixes #40159
1 parent f3fc547 commit 23382e6

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

src/libstd/path.rs

+35-1
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,17 @@
5151
//! ```
5252
//! use std::path::PathBuf;
5353
//!
54+
//! // This way works...
5455
//! let mut path = PathBuf::from("c:\\");
56+
//!
5557
//! path.push("windows");
5658
//! path.push("system32");
59+
//!
5760
//! path.set_extension("dll");
61+
//!
62+
//! // ... but push is best used if you don't know everything up
63+
//! // front. If you do, this way is better:
64+
//! let path: PathBuf = ["c:\\", "windows", "system32.dll"].iter().collect();
5865
//! ```
5966
//!
6067
//! [`Component`]: ../../std/path/enum.Component.html
@@ -63,6 +70,7 @@
6370
//! [`Path`]: ../../std/path/struct.Path.html
6471
//! [`push`]: ../../std/path/struct.PathBuf.html#method.push
6572
//! [`String`]: ../../std/string/struct.String.html
73+
//!
6674
//! [`str`]: ../../std/primitive.str.html
6775
//! [`OsString`]: ../../std/ffi/struct.OsString.html
6876
//! [`OsStr`]: ../../std/ffi/struct.OsStr.html
@@ -1036,14 +1044,40 @@ impl<'a> cmp::Ord for Components<'a> {
10361044
///
10371045
/// # Examples
10381046
///
1047+
/// You can use [`push`] to build up a `PathBuf` from
1048+
/// components:
1049+
///
10391050
/// ```
10401051
/// use std::path::PathBuf;
10411052
///
1042-
/// let mut path = PathBuf::from("c:\\");
1053+
/// let mut path = PathBuf::new();
1054+
///
1055+
/// path.push(r"C:\");
10431056
/// path.push("windows");
10441057
/// path.push("system32");
1058+
///
10451059
/// path.set_extension("dll");
10461060
/// ```
1061+
///
1062+
/// However, [`push`] is best used for dynamic situations. This is a better way
1063+
/// to do this when you know all of the components ahead of time:
1064+
///
1065+
/// ```
1066+
/// use std::path::PathBuf;
1067+
///
1068+
/// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
1069+
/// ```
1070+
///
1071+
/// We can still do better than this! Since these are all strings, we can use
1072+
/// `From::from`:
1073+
///
1074+
/// ```
1075+
/// use std::path::PathBuf;
1076+
///
1077+
/// let path = PathBuf::from(r"C:\windows\system32.dll");
1078+
/// ```
1079+
///
1080+
/// Which method works best depends on what kind of situation you're in.
10471081
#[derive(Clone)]
10481082
#[stable(feature = "rust1", since = "1.0.0")]
10491083
pub struct PathBuf {

0 commit comments

Comments
 (0)