获取文件所在文件夹

Get the containing folder of a file

我正在尝试提取 Rust 文件的包含文件夹。有什么方法可以从 String 获取包含文件夹吗?例如,下面的代码可以工作,但是很乱:

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);

有内置类型,PathPathBuf 为此:

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());

您通常不需要像我上面那样将 PathPathBuf 转换回 &strString,因为大多数std API 将直接接受它们。