Get the containing folder of a file

Viewed 1374

I am trying to extract the containing folder of a file in Rust. Is there any way to go from a String to getting the containing folder? For example, the following code works, however it is messy:

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

There are built-in types, Path and PathBuf for this:

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

You don't usually need to convert a Path or PathBuf back to a &str or String, as I have done above, because most of the std APIs will accept them directly.

Related