DEV Community

BC
BC

Posted on

Day33:and_then,map_or,unwrap_or - 100DayOfRust

We can apply and_then, map_or, unwrap_or functions to an Option value:

  • and_then: take the wrapped value as parameter if Some, return another Option value; or return None if None
  • map_or: return a fallback value if None, and run a mapping function for Some
  • map_or_else: run a fallback function if None, and a mapping function for Some
  • unwrap_or: return a fallback value if None, or unwrap the value if Some
  • unwrap_or_else: run a fallback function if None, or unwrap the value if Some

Example

fn main() {
    let x = Some(4);

    // calculate 2*x + 3
    // we can and_then functions
    let result = x.and_then(|v| {
        Some(v * 2)
    }).and_then(|v| {
        Some(v + 3)
    });
    println!("#1: {}", result.unwrap());

    // map_or and map_or_else
    println!("#2: {}", result.map_or(42, |v| {
        v * v
    }));
    println!("#3: {}", result.map_or_else(
        || {42}, 
        |v| {v * v}
    ));

    // unwrap_or and unwrap_or_else
    println!("#4: {}", result.unwrap_or(42));
    println!("#5: {}", result.unwrap_or_else(|| {42}));
    println!("#6: {}", None.unwrap_or(42));
}
Enter fullscreen mode Exit fullscreen mode

Result:

#1: 11
#2: 121
#3: 121
#4: 11
#5: 11
#6: 42
Enter fullscreen mode Exit fullscreen mode

Reference

Top comments (0)