Tri*_*yPR 8 filesystems path rust
我正在尝试提取 Rust 中文件的包含文件夹。有什么办法可以从 aString
到获取包含的文件夹吗?例如,下面的代码可以工作,但是很混乱:
let path = "/path/to/file.txt";
let mut path_arr: Vec<&str> = path.split('/').collect();
path_arr.pop();
let new_string = path_arr.join("/");
assert_eq!("/path/to", new_string);
Run Code Online (Sandbox Code Playgroud)
有内置类型,Path
为此PathBuf
:
use std::path::PathBuf;
let path = PathBuf::from("/path/to/file.txt");
let dir = path.parent().unwrap();
assert_eq!("/path/to", dir.to_str().unwrap());
Run Code Online (Sandbox Code Playgroud)
您通常不需要像我上面所做的那样将 a Path
or转换PathBuf
回&str
or String
,因为大多数std
API 都会直接接受它们。