Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have a function that calls another function which returns a Result. I need to check if the Result is Ok or Err and if it is an Err, I need to return early from my function. This is what I'm doing now:

match callable(&mut param) {
    Ok(_v) => (),
    Err(_e) => return,
};

Is there a more idiomatic Rust way to do this?

like image 315
Josh Abraham Avatar asked Jul 15 '18 03:07

Josh Abraham


People also ask

How do you unwrap error in Rust?

To “unwrap” something in Rust is to say, “Give me the result of the computation, and if there was an error, panic and stop the program.” It would be better if we showed the code for unwrapping because it is so simple, but to do that, we will first need to explore the Option and Result types.

What is OK function in Rust?

It is an enum with the variants, Ok(T) , representing success and containing a value, and Err(E) , representing error and containing an error value. enum Result<T, E> { Ok(T), Err(E), } Functions return Result whenever errors are expected and recoverable. In the std crate, Result is most prominently used for I/O.


2 Answers

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!");
    }
}
like image 176
Boiethios Avatar answered Sep 20 '22 07:09

Boiethios


You can use my unwrap_or crate to accomplish this.

You can do:

unwrap_or_ok!(callable(&mut param), _, return);

And if you want the result and to return the error, you can do:

let v = unwrap_or_ok!(callable(&mut param), error, return error);
like image 2
Stephen Hurley Avatar answered Sep 22 '22 07:09

Stephen Hurley