= parseA(); let...">

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, band cfor example Scala for-expression?

+6
source share
1 answer

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 Resultin a variable.

+3
source

Source: https://habr.com/ru/post/1014577/


All Articles