1

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.

Poliakoff
  • 1,592
  • 1
  • 21
  • 40
justin.m.chase
  • 13,061
  • 8
  • 52
  • 100
  • 2
    `let v = foo()?` will propagate the error up. See [this](https://doc.rust-lang.org/edition-guide/rust-2018/error-handling-and-panics/the-question-mark-operator-for-easier-error-handling.html) example in the rust documentation. – elliptic_hyperboloid Jul 08 '20 at 17:50
  • 1
    **Please** take the time to read [*The Rust Programming Language*](https://doc.rust-lang.org/book/). In this case, [Recoverable Errors with Result](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html). – Shepmaster Jul 08 '20 at 17:59
  • This is the relevant part: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator – justin.m.chase Jul 08 '20 at 18:01

1 Answers1

6

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);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366