rust path module grand parent (several levels up)

Viewed 91

Is there a better way of getting an ancestor several levels up in the folder structure hierarchy using std::path::Path?

At the moment if want to get the ancestor which is 5 levels up, I do the following (see below) but I feel there must be a better way.

I am aware of the method ancestors but I couldn't see how to use it to improve this snippet.

use std::path::PathBuf;

let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let ancestor_dir = out_dir
    .parent()
    .unwrap()
    .parent()
    .unwrap()
    .parent()
    .unwrap()
    .parent()
    .unwrap()
    .parent()
    .unwrap();

Can this be written in a more readable way?

1 Answers

ancestors() produces an iterator over Path and its ancestors. An iterator has a method called nth which you can use to return nth element of the iterator.

use std::path::Path;

fn main() {
    let out_dir = Path::new("/foo/bar/lev1/lev2/lev3/lev4");
    let ancestor_dir = out_dir.ancestors().nth(5).unwrap();
    println!("{}", ancestor_dir.display())
}
Related