I read that using unwrap
on a Result
is not a good practice in Rust and that it's better to use pattern matching so any error that occurred can be handled appropriately.
I get the point, but consider this snippet that reads a directory and prints the accessed time for each entry:
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")
}
}
I want to handle every possible error in the code above (the panic
macro is just a placeholder). While the code above works, I think it's ugly. What is the idiomatic way to handle a case like this?