]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/std_misc/path.md
New upstream version 1.55.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / std_misc / path.md
CommitLineData
2c00a5a8
XL
1# Path
2
3The `Path` struct represents file paths in the underlying filesystem. There are
4two flavors of `Path`: `posix::Path`, for UNIX-like systems, and
5`windows::Path`, for Windows. The prelude exports the appropriate
6platform-specific `Path` variant.
7
8A `Path` can be created from an `OsStr`, and provides several methods to get
9information from the file/directory the path points to.
10
11Note that a `Path` is *not* internally represented as an UTF-8 string, but
12instead is stored as a vector of bytes (`Vec<u8>`). Therefore, converting a
13`Path` to a `&str` is *not* free and may fail (an `Option` is returned).
14
15```rust,editable
16use std::path::Path;
17
18fn main() {
19 // Create a `Path` from an `&'static str`
20 let path = Path::new(".");
21
136023e0 22 // The `display` method returns a `Display`able structure
2c00a5a8
XL
23 let _display = path.display();
24
25 // `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");
28
29 // Convert the path into a string slice
30 match new_path.to_str() {
31 None => panic!("new path is not a valid UTF-8 sequence"),
32 Some(s) => println!("new path is {}", s),
33 }
34}
35
36```
37
38Be sure to check at other `Path` methods (`posix::Path` or `windows::Path`) and
39the `Metadata` struct.
40
e1599b0c 41### See also:
2c00a5a8
XL
42
43[OsStr][1] and [Metadata][2].
44
45[1]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html
46[2]: https://doc.rust-lang.org/std/fs/struct.Metadata.html