我正在尝试写一个特性,这将允许我"解包"多个嵌套Option<Option<...<T>>>>到单个,Option<T>以更好地使用我正在使用的API.我正在尝试创建一个通用解决方案,但我无法弄清楚如何使其工作.
这是我的许多尝试之一:
trait UnwrapOption<T> {
fn unwrap_opt(self) -> Option<T>;
}
impl<T> UnwrapOption<T> for Option<T> {
fn unwrap_opt(self) -> Option<T> {
self
}
}
impl<T> UnwrapOption<T> for Option<Option<T>> {
fn unwrap_opt(self) -> Option<T> {
match self {
Some(e) => e.unwrap_opt(),
None => None,
}
}
}
fn main() {
let x = Some(Some(Some(1)));
println!("{:?}", x.unwrap_opt());
}
Run Code Online (Sandbox Code Playgroud) 我读到使用unwrapon Result在Rust中不是一个好习惯,并且最好使用模式匹配,因此可以适当地处理发生的任何错误.
我明白了这一点,但考虑一下读取目录的片段并打印每个条目的访问时间:
use std::fs;
use std::path::Path;
fn main() {
let path = Path::new(".");
match fs::read_dir(&path) {
Ok(entries) => {
for entry in entries {
match entry {
Ok(ent) => {
match ent.metadata() {
Ok(meta) => {
match meta.accessed() {
Ok(time) => {
println!("{:?}", time);
},
Err(_) => panic!("will be handled")
}
},
Err(_) => panic!("will be handled")
}
},
Err(_) => panic!("will be handled")
}
}
},
Err(_) => panic!("will be handled")
}
}
Run Code Online (Sandbox Code Playgroud)
我想处理上面代码中的每个可能的错误(panic …