|
51 | 51 | //! ```
|
52 | 52 | //! use std::path::PathBuf;
|
53 | 53 | //!
|
| 54 | +//! // This way works... |
54 | 55 | //! let mut path = PathBuf::from("c:\\");
|
| 56 | +//! |
55 | 57 | //! path.push("windows");
|
56 | 58 | //! path.push("system32");
|
| 59 | +//! |
57 | 60 | //! 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(); |
58 | 65 | //! ```
|
59 | 66 | //!
|
60 | 67 | //! [`Component`]: ../../std/path/enum.Component.html
|
|
63 | 70 | //! [`Path`]: ../../std/path/struct.Path.html
|
64 | 71 | //! [`push`]: ../../std/path/struct.PathBuf.html#method.push
|
65 | 72 | //! [`String`]: ../../std/string/struct.String.html
|
| 73 | +//! |
66 | 74 | //! [`str`]: ../../std/primitive.str.html
|
67 | 75 | //! [`OsString`]: ../../std/ffi/struct.OsString.html
|
68 | 76 | //! [`OsStr`]: ../../std/ffi/struct.OsStr.html
|
@@ -1036,14 +1044,40 @@ impl<'a> cmp::Ord for Components<'a> {
|
1036 | 1044 | ///
|
1037 | 1045 | /// # Examples
|
1038 | 1046 | ///
|
| 1047 | +/// You can use [`push`] to build up a `PathBuf` from |
| 1048 | +/// components: |
| 1049 | +/// |
1039 | 1050 | /// ```
|
1040 | 1051 | /// use std::path::PathBuf;
|
1041 | 1052 | ///
|
1042 |
| -/// let mut path = PathBuf::from("c:\\"); |
| 1053 | +/// let mut path = PathBuf::new(); |
| 1054 | +/// |
| 1055 | +/// path.push(r"C:\"); |
1043 | 1056 | /// path.push("windows");
|
1044 | 1057 | /// path.push("system32");
|
| 1058 | +/// |
1045 | 1059 | /// path.set_extension("dll");
|
1046 | 1060 | /// ```
|
| 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. |
1047 | 1081 | #[derive(Clone)]
|
1048 | 1082 | #[stable(feature = "rust1", since = "1.0.0")]
|
1049 | 1083 | pub struct PathBuf {
|
|
0 commit comments