[英]rust path module grand parent (several levels up)
Is there a better way of getting an ancestor several levels up in the folder structure hierarchy using std::path::Path ?有没有更好的方法使用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.目前如果想获得5级以上的祖先,我做了以下(见下文)但我觉得必须有更好的方法。
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?这可以写成更易读的方式吗?
ancestors()
produces an iterator over Path
and its ancestors. Ancients() 在Path
及其祖先上ancestors()
一个迭代器。 An iterator has a method called nth
which you can use to return nth
element of the iterator.迭代器有一个名为nth
的方法,您可以使用该方法返回迭代器的nth
元素。
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())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.