this post was submitted on 23 Nov 2023
41 points (91.8% liked)

Rust

5981 readers
24 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS
 

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!

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 3 points 11 months 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 ResultᐸOptionᐸTᐳᐳs and OptionᐸResultᐸTᐳᐳs