How can I briefly combine many "results" of different types?
I am currently using this template:
let a: Result<A, ParseError> = parseA();
let b: Result<B, ParseError> = parseB();
let c: Result<C, ParseError> = parseC();
a.and_then(|a| b.map(|b| (a, b))).and_then(|(a,b)| c.map(|c| {
// finally the crux of what I want to do
a.foo(b).bar(c)
}))
Is there a shorter way to define a
, b
and c
for example Scala for-expression?
I usually wrap everything in layers instead of chaining through tuples:
let result = a.and_then(|a| {
b.and_then(|b| {
c.map(|c| {
a.foo(b).bar(c)
})
})
});
Or, in recent versions of Rust, you can use the operator in detail ?
:
let result = a.and_then(|a| {
a.foo(b?).bar(c?)
});
Closing allows you to do this beautifully and safely.
Of course, this does not work if you want to save the intermediate Result
in a variable.