Hacker News new | ask | show | jobs
by steveklabnik 16 days ago
Rust makes you define an enum of E, F, and G, but also provides a conversion API so you can pass any of the three and it feels like it does, at least at the site of returning the error.

It also provides an error interface so sometimes you don’t need the enum, if all the types return that interface.

1 comments

Wouldn't you lose a little compile time safety a little by returning the interface, like catching Exception?

i.e. as types you don't know about get introduced the compiler won't stop bad things from happening:

    catch (Exception ex) {
        switch (ex) {
            case SomeException1 se1 -> ..
            case SomeException2 se2 -> ..
            default -> throw new IllegalStateException(ex); // panic
        }
    }
Depends on what you mean by "safety," what this is really about is open vs closed set. An interface means that there's an open set of things that could be returned, whereas an enum is a closed set. Which one is correct for you depends on your code and requirements.

It's true that if you return an open set of things, you'll have to handle cases you didn't explicitly account for.

I just meant knowing what errors can be happen at compile time vs unchecked errors flying about. I personally am not a fan of the compiler not stopping me when a new error type is introduced. Correctness is probably the better word.