【发布时间】:2016-10-01 11:06:12
【问题描述】:
我读到在 Result 上使用 unwrap 在 Rust 中不是一个好的做法,最好使用模式匹配,以便可以适当地处理发生的任何错误。
我明白了,但是考虑一下这个读取目录并打印每个条目的访问时间的 sn-p:
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")
}
}
我想处理上面代码中所有可能的错误(panic 宏只是一个占位符)。虽然上面的代码有效,但我认为它很难看。处理这种情况的惯用方法是什么?
【问题讨论】:
标签: coding-style rust