1

I'm trying to return an Err when any step of initialization returns an Err:

fn init<'r>(&self) -> Result<(), ()> {
    match self.check_1() {
        Err(e) => return Err(e),
        _ => {}
    };
    match self.check_2() {
        Err(e) => return Err(e),
        _ => {}
    };
    // [more checks]
    return Ok(());
}

To me, this is cluttered. SQL has ifnull or coalesce which returns the first non-null result. As can be seen, I'm trying to do that, but return the first Err.

Is there any syntax or macro that will enable me to return the first Err encountered, while not executing subsequent check functions, i.e. short-circuiting the check evaluation logic?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ross Rogers
  • 23,523
  • 27
  • 108
  • 164
  • 2
    Consider re-reading *The Rust Programming Language* — [Recoverable Errors with Result](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html) – Shepmaster Jun 23 '20 at 16:53
  • 1
    See also the `if let` syntax. For maximum idiomatic usage, remove the explicit `return` keyword. – Shepmaster Jun 23 '20 at 16:55
  • Thanks @Shepmaster for the ridiculously fast response. I really appreciate your attention to this question. Please consider marking as duplicate because this question is a reasonable artifact to point people to a the question mark operator. I spent 20 minutes asking google questions along these lines and there aren't great results coming from this SQL ifnull mental model. I don't care about the points or whatever, but the artifact may be useful to others. Or don't. Thanks for the answer! – Ross Rogers Jun 23 '20 at 16:59
  • 1
    Applying the question mark — `fn init(&self) -> Result<(), ()> { self.check_1()?; self.check_2()?; Ok(()) }`. – Shepmaster Jun 23 '20 at 17:00
  • Yup. That makes sense. – Ross Rogers Jun 23 '20 at 17:01
  • @Shepmaster . Can I ask you another stupid question? Can I return the contained value of an `Err` if a function returns an `Err` without a `match` ? Is there something more idiomatic than `match self.init() { Err(e) => return e, _ => {} }` – Ross Rogers Jun 23 '20 at 17:49
  • 1
    You want to return the error value, but no longer wrapped in a `Result`? That's not typical, no. As mentioned earlier, I'd use an `if let`, but otherwise nothing is coming to mind. – Shepmaster Jun 23 '20 at 17:57
  • `if let`. That would be better. – Ross Rogers Jun 23 '20 at 17:59

0 Answers0