How to flatten two Result

Viewed 834

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.

1 Answers

You are looking for Result::and_then:

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