42
submitted 10 months ago by kia@lemmy.ca to c/rust@programming.dev

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
[-] BB_C@programming.dev 4 points 10 months 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).

this post was submitted on 23 Nov 2023
42 points (92.0% liked)

Rust

5777 readers
7 users here now

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

Wormhole

!performance@programming.dev

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