Is there a way to chain Result mapping and unwrapping?
If you actually want to ignore the results as you are doing with if let
you can use a macro like this:
macro_rules! iflet {
([$p:pat = $e:expr] $($rest:tt)*) => {
if let $p = $e {
iflet!($($rest)*);
}
};
($b:block) => {
$b
};
}
fn main() {
iflet!([Ok(file) = env::var("CONF")]
[Ok(mut reader) = File::open(&file)]
[Ok(conf) = Json::from_reader(&mut reader)] {
// do something with conf
});
}
Playground (without Json part)
The macro is originally from an answer I made to a similar question on Option
s, but it works with any if let
. Though, with Result
you often want to use the Err
in some way, so I would usually lean towards the approach explained by Shepmaster or ?
/try!
.
Is there such a mechanism in Rust?
Yes — although not all in one shot like you've presented. Let's review your theoretical signature:
impl<T, E> Result<T, E> {
fn map_unwrap<F, U, D>(&self, op: F) -> Result<U, D>
where
F: FnOnce(T) -> Result<U, D>,
{}
}
This cannot work - assume that we start with an Err
variant - how would this code know how to convert from E
to D
? Additionally, &self
isn't appropriate for functions that want to convert types; those usually take self
.
There are two components that you will need to combine:
Result::and_then
impl<T, E> Result<T, E> { fn and_then<U, F>(self, op: F) -> Result<U, E> where F: FnOnce(T) -> Result<U, E>, {} }
Result::map_err
impl<T, E> Result<T, E> { fn map_err<F, O>(self, op: O) -> Result<T, F> where O: FnOnce(E) -> F, {} }
Then you will need a type that can represent both error types. I'll be lazy and use Box<Error>
Combined together, you need something like:
use std::env;
use std::fs::File;
use std::error::Error;
fn main() {
let conf = env::var("CONF")
.map_err(|e| Box::new(e) as Box<Error>)
.and_then(|f| File::open(f).map_err(|e| Box::new(e) as Box<Error>));
}
Now each call converts the error value to a shared type, and the result is chainable with and_then
. Presumably, your real code would create an error type that is suited to your problem, and then you would use that in the map_err
call. I'd implement From
, then you can have just:
let conf: Result<_, Box<Error>> = env::var("CONF")
.map_err(Into::into)
.and_then(|f| File::open(f).map_err(Into::into));