Rust 编程中的路径结构
Rust中的Pathstruct用于表示底层文件系统中的文件路径。还应该注意的是,Rust中的Path不表示为UTF-8字符串;相反,它存储为字节向量(Vec
示例
考虑下面显示的例子-
use std::path::Path;
fn main() {
// Create a `Path` from an `&'static str`
let path = Path::new(".");
//`display`方法返回一个`Show`able结构
let display = path.display();
//检查路径是否存在
if path.exists() {
println!("{} exists", display);
}
//检查路径是否为文件
if path.is_file() {
println!("{} is a file", display);
}
//检查路径是否为目录
if path.is_dir() {
println!("{} is a directory", display);
}
//`join`使用特定于操作系统的字节容器合并路径
//分隔符,并返回新路径
let new_path = path.join("a").join("b");
//将路径转换为字符串切片
match new_path.to_str() {
None => panic!("new path is not a valid UTF-8 sequence"),
Some(s) => println!("new path is {}", s),
}
}输出
如果我们运行上面的代码,我们将看到以下输出-
. exists . is a directory new path is ./a/b