RRust By Example
intermediateError Handling

Result Combinators

Chain operations on Result with map, and_then, or_else.

Result Combinators

Chain operations on Result with map, and_then, or_else.

Difficulty

Intermediate

Code

rust
use std::num::ParseIntError;

fn double_parse(input: &str) -> Result<i32, String> {
    input.trim()
        .parse::<i32>()
        .map(|n| n * 2)
        .map_err(|e| format!("parse error: {}", e))
}

fn main() {
    // map transforms the Ok value
    let x = double_parse("21");
    println!("double 21 = {:?}", x);

    // map_err transforms the Err value
    let x = double_parse("abc");
    println!("double abc = {:?}", x);

    // and_then chains fallible operations
    let result = "42"
        .parse::<i32>()
        .and_then(|n| Ok(n * 2))
        .and_then(|n| Ok(n + 1));
    println!("result: {:?}", result);

    // unwrap_or provides default
    let x: i32 = "abc".parse().unwrap_or(0);
    println!("default: {}", x);
}

Explanation

Chain Result operations with map, and_then, unwrap_or.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the error-handling category to build a complete understanding of this topic.

More Error Handling Examples