Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I hope Go will eventually get sum types but I hope they're better than Rust's where each variant is its own type.


How is this mess better than Rust's enums? A Rust enum + match statement results in really easy to read and clean code.


For a trivial example, let's say I have some message type that has multiple variants with differing fields:

    enum Message {
        Action1(String, Option<Mode>),
        Action2(String),
    }
Action1 and Action2 are variants not types and I cannot make functions that take an Action1 or an Action2 as a parameter. To get around this people will often make each enum variant just a container for some struct with the same name but that's more verbose and matching becomes slightly uglier. Code like this is fairly common:

    struct Action1(String, Option<Mode>);

    struct Action2(String);

    enum Message {
        Action1(Action1),
        Action2(Action2),
    }
Ideally I'd like to be able to succinctly say something like:

    type A = B | C
and have A be dependent on B and C but have both B and C be completely independent types.


That is a pretty compelling point... I ran into this less than an hour ago and was slightly frustrated.

Though, I still like the flexibility of adding additional fields to `Action1`. In golang I end up with fields that are conditionally populated based on the state of an Enum which is less than ideal and leads to lots of error checking (though this is relatively rare).

It doesn't have to be one or the other though. A bit more polishing on the Rust-style enums (perhaps in a different language) could lead to pretty ergonomic code.


> Rust's where each variant is its own type.

Is this... right? You can't use enum variants as types in function signatures, variable declarations, etc.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: