获取文件所在的文件夹

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)

Pet*_*all 9

有内置类型,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 Pathor转换PathBuf&stror String,因为大多数stdAPI 都会直接接受它们。