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

Rust

5749 readers
172 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] 5 points 10 months ago (1 children)

Unwaps or panicing or returning the error to the caller are all forms of handling the error - crash the program with a message that can tell you what went wrong and where in the code it happened. These give you a path to see what went wrong

But silently ignoring an error is rarely the right move. It stops you from seeing what the cause of the problem is and often leads to some weird non sensical failure somewhere else. Which I have seen time and time again lead to hours down a rabbit hole trying to understand why things are not working because you are missing the root cause of the problem.

There are times when you really don't care about a failure at all, but those times are rare and should be carefully considered first, crashing the program is generally the first thing you should do if you are unsure.

[โ€“] [email protected] 3 points 10 months ago

Fair enough. I didn't consider "just crash lol" as handling the error, but your distinction is a good one.