Skip to content

Commit ec954f3

Browse files
authored
Merge pull request #1519 from Spoonbender/1260-pathbuf
PathBuf details and example
2 parents 4451ac0 + 2851fac commit ec954f3

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

src/std_misc/path.md

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ platform-specific `Path` variant.
88
A `Path` can be created from an `OsStr`, and provides several methods to get
99
information from the file/directory the path points to.
1010

11+
A `Path` is immutable. The owned version of `Path` is `PathBuf`. The relation
12+
between `Path` and `PathBuf` is similar to that of `str` and `String`:
13+
a `PathBuf` can be mutated in-place, and can be dereferenced to a `Path`.
14+
1115
Note that a `Path` is *not* internally represented as an UTF-8 string, but
1216
instead is stored as a vector of bytes (`Vec<u8>`). Therefore, converting a
1317
`Path` to a `&str` is *not* free and may fail (an `Option` is returned).
@@ -23,10 +27,17 @@ fn main() {
2327
let _display = path.display();
2428
2529
// `join` merges a path with a byte container using the OS specific
26-
// separator, and returns the new path
27-
let new_path = path.join("a").join("b");
30+
// separator, and returns a `PathBuf`
31+
let mut new_path = path.join("a").join("b");
32+
33+
// `push` extends the `PathBuf` with a `&Path`
34+
new_path.push("c");
35+
new_path.push("myfile.tar.gz");
36+
37+
// `set_file_name` updates the file name of the `PathBuf`
38+
new_path.set_file_name("package.tgz");
2839
29-
// Convert the path into a string slice
40+
// Convert the `PathBuf` into a string slice
3041
match new_path.to_str() {
3142
None => panic!("new path is not a valid UTF-8 sequence"),
3243
Some(s) => println!("new path is {}", s),

0 commit comments

Comments
 (0)