So Result<T, E> has a pretty neat method map_err that allows to handle errors in a functional way:
use std::io::Result;
use std::error::Error;
use std::string::ToString;
use std::io;
fn init() -> Result<u32> { Ok(42) }
fn do_work(_data: u32) -> Result<()> { Err(io::Error::new(io::ErrorKind::Other, "IO Error!")) }
fn handle_error<E: Error + ToString>(error: E, message: &str) -> E {
eprintln!("{}: {}", message, error.to_string());
error
}
fn main() {
let _ = init()
.map_err(|e| handle_error(e, "Init error"))
.and_then(do_work)
.map_err(|e| handle_error(e, "Work error")); // "Work error: IO error"
}
It would be cool to have the same functional style for handling Option<T>::None:
use std::io::Result;
use std::error::Error;
use std::string::ToString;
use std::io;
fn init_opt() -> Option<u32> { Some(42) }
fn do_work_opt(_data: u32) -> Option<()> { None }
fn handle_none(message: &str) {
eprintln!("{}", message);
}
fn main() {
let _ = init_opt()
.map_none(|| handle_none("Init error"))
.and_then(do_work_opt)
.map_none(|| handle_none("Work error")); // "Work error"
}
But I don't see any suitable replacement for this method in documentation of Option
It can be done with a custom trait like that
trait MapNone {
fn map_none(self, op: impl FnOnce() -> ()) -> Self;
}
impl<T> MapNone for Option<T> {
fn map_none(self, op: impl FnOnce() -> ()) -> Self {
if self.is_none() { op(); }
self
}
}
But I'm sure I'm missing something and there is some pretty way of doing the same via standard library.