Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cleanest way to return the error when matching a Result<T, E>? [duplicate]

I'm calling a function that returns a Result<T, E> and I want to handle the Ok case but return the Err as is if an error is returned. What is the cleanest way to do this?

For example, I have:

fn example() -> Result<(), Error> {
    match foo() {
        Ok(v) => bar(v),
        Err(e) => Err(e),
    }
}

What are some alternate forms of writing this? It feels weird to re-wrap e in another Err in every call in the stack. Also, every call is basically 4 lines of boilerplate... I'm just looking for a way to simplify and make it more readable. My desire is to have it return the error if error, else process the result value.

like image 794
justin.m.chase Avatar asked Oct 28 '25 09:10

justin.m.chase


1 Answers

Rust includes an 'error propagation' operator, ?. If the value of the Result it is called on is Ok it will unwrap and return the inner value. If the value is Err it will return from the function and pass the Err to the caller.

fn example() -> Result<(), Error> {
    let v = foo()?;
    bar(v);
}
like image 140
elliptic_hyperboloid Avatar answered Oct 30 '25 07:10

elliptic_hyperboloid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!