This is a really simple silly thing I just realized, but I noticed I have a lot code that looks something like this:

fn foo() -> Result<(), Error> {
    // do something
}

fn bar() -> Option<()> {
    let Ok(f) = foo() else {
        return None;
    };
}

I hated that if-statement. I realized today that I could simplify to:

fn bar() -> Option<()> {
    let f = foo().ok()?;
}

And that cleaned up my code a lot. It’s a tiny thing, but when it’s okay to discard the error from the result, makes such a big difference when you have a lot of them!

  • tatterdemalion@programming.dev
    link
    fedilink
    arrow-up
    16
    ·
    2 years ago

    Do you really discard errors this often? I would say almost all of my Results get propagated to the caller via ? and handled in one place near the start of the stack.

    • kia@lemmy.caOP
      link
      fedilink
      English
      arrow-up
      2
      ·
      2 years ago

      A lot of the time, I have these around places where I’m reading from a file. If reading causes an error, regardless of what the error is, I just return None and a new file is created.

      • nous@programming.dev
        link
        fedilink
        English
        arrow-up
        12
        ·
        2 years ago

        That is a terrible time to throw away the error. Best to actually check for file not exists error and created the file only then. Other errors are important to see to debug why things are failing.

        It is very annoying to have a tool tell you it failed to create a file when the file exists but it just cannot read it for some reason. You can spend ages jumping down the wrong rabbit whole if you don’t realize what is happening.

        • BB_C@programming.dev
          link
          fedilink
          arrow-up
          3
          ·
          2 years ago

          That is a terrible time to throw away the error. Best to actually check for file not exists error and…

          lol

          This is unintentionally funny considering how exists() is implemented (which is why we have try_exists() now).

        • kia@lemmy.caOP
          link
          fedilink
          English
          arrow-up
          1
          ·
          2 years ago

          Yeah that’s a good point. This is a special case where the file is simply caching runtime results so errors surrounding it not being read aren’t a big deal.

      • BB_C@programming.dev
        link
        fedilink
        arrow-up
        2
        ·
        2 years ago

        I don’t get it!

        If the T in Result (and presumably Option) is (), then why not just use is_ok()/is_err() from the caller side?

        Other Tips:

        • bool has then() and then_some() methods in std now.
        • You can transpose() in both directions between ResultOptionᐸTᐳᐳs and OptionResultᐸTᐳᐳs