2

Given the two functions below, how can I "flatten" the two Result into a single one?

fn result1() -> Result<u8, String> {
  Ok(10)
}

fn result2(number: u8) -> Result<u8, String> {
  Ok(number * 2)
}

So, running the following code:

fn main() {
    let result = result1().map(|number| result2(number));
    println!("{:?}", result);
    // Output: Ok(Ok(20))
}

I get the same result as this code:

fn main() {
    let result = result1().map(|number| number * 2);
    println!("{:?}", result);
    // Output: Ok(20)
}

Notice the nested Ok Ok(Ok(20)) instead of the correct single Ok Ok(20).

Something similar to what I'm looking for is the Rx flatmap, but as I'm studying rust I would like to get the job done using the language mindset.

ademar111190
  • 14,215
  • 14
  • 85
  • 114

1 Answers1

4

You are looking for Result::and_then:

fn main() {
    let result = result1().and_then(result2);
    println!("{:?}", result);
    // Output: Ok(20)
}
Kitsu
  • 3,166
  • 14
  • 28
  • 1
    Thank you, I did not try `and_then` before because its behaviour is completely different from the Rxs `andThen`. That is one nice thing about learning a new language :) – ademar111190 Jul 05 '20 at 21:45