How do you unwrap a Result on Ok or return from the function on Err?

You can create a macro:

macro_rules! unwrap_or_return {
    ( $e:expr ) => {
        match $e {
            Ok(x) => x,
            Err(_) => return,
        }
    }
}

fn callable(param: &mut i32) -> Result<i32, ()> {
    Ok(*param)
}

fn main() {
    let mut param = 0;
    let res = unwrap_or_return!(callable(&mut param));

    println!("{:?}", res);
}

Note that I wouldn’t recommend discarding the errors. Rust’s error handling is pretty ergonomic, so I would return the error, even if it is only to log it:

fn callable(param: &mut i32) -> Result<i32, ()> {
    Ok(*param)
}

fn run() -> Result<(), ()> {
    let mut param = 0;
    let res = callable(&mut param)?;

    println!("{:?}", res);

    Ok(())
}

fn main() {
    if let Err(()) = run() {
        println!("Oops, something went wrong!");
    }
}

Leave a Comment