路径

Path 结构体表示底层文件系统中的文件路径。Path 有两种形式:posix::Path,用于类 UNIX 系统;以及 windows::Path,用于 Windows 系统。 prelude 导出了适合特定平台的 Path 变体。

可以从 OsStr 创建 Path,并提供了几个方法来获取路径指向的文件/目录的信息。

Path 是不可变的。Path 的拥有版本是 PathBufPathPathBuf 之间的关系类似于 strString 之间的关系:PathBuf 可以原地修改,并且可以解引用为 Path

请注意,Path 在内部不是表示为 UTF-8 字符串,而是存储为 OsString。因此,将 Path 转换为 &str 不是免费的,并且可能会失败(返回 Option)。但是,可以使用 into_os_stringas_os_str 分别将 Path 自由地转换为 OsString&OsStr

use std::path::Path;

fn main() {
    // Create a `Path` from an `&'static str`
    let path = Path::new(".");

    // The `display` method returns a `Display`able structure
    let _display = path.display();

    // `join` merges a path with a byte container using the OS specific
    // separator, and returns a `PathBuf`
    let mut new_path = path.join("a").join("b");

    // `push` extends the `PathBuf` with a `&Path`
    new_path.push("c");
    new_path.push("myfile.tar.gz");

    // `set_file_name` updates the file name of the `PathBuf`
    new_path.set_file_name("package.tgz");

    // Convert the `PathBuf` into a string slice
    match new_path.to_str() {
        None => panic!("new path is not a valid UTF-8 sequence"),
        Some(s) => println!("new path is {}", s),
    }
}

请务必查看其他 Path 方法(posix::Pathwindows::Path)和 Metadata 结构体。

另请参阅

OsStrMetadata