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

I'm not an expert in Rust, so some of these things might be available in it's match (just in a way I'm unfamiliar with), but for me the big advantages of Swift's switch are:

- switching on tuples (not wrapped in a var): this prevents doubly-nested switches, which I've always found to be a problem in control logic. - unwrapping optionals - matching against an enum's associated value, and unwrapping it - using `where` clauses as part of the pattern - matching against type casts



Rust has all that functionality, but as the author mentioned, they avoided using enums and match statements because it led to more runtime errors and they were specifically trying to incur compile time errors. This is why they choose to use trait objects and type definitions to control state transitions.

Edit: I invite you to learn more about the match keyword in rust and see how it relates to swift. I think you’ll find that it meets or exceeds your expectations: https://doc.rust-lang.org/book/ch06-02-match.html


Aside from the last, this is all very standard stuff, I don't mean for Rust I mean for language with sum types in general.

> - switching on tuples (not wrapped in a var): this prevents doubly-nested switches, which I've always found to be a problem in control logic

    match t {
        (Some(a), Some(b)) => a + b,
        (Some(a), None) => a,
        (None, Some(b)) => b,
        (None, None) => 0
    }
                      
> - unwrapping optionals

    match opt {
        Some(v) => v,
        None => 0
    }
although it's common to use HOFs, the `?` operator, or `if let`.

> - matching against an enum's associated value, and unwrapping it

See above.

- using `where` clauses as part of the pattern

    match opt {
        Some(v) if v > 5 => v - 5,
        Some(v) => v,
        None => 0
    }
> - matching against type casts

Rust doesn't really do subtyping, so that's not a case which would come up. I guess the closest would be matching on the result of a downcast_ref (https://doc.rust-lang.org/std/any/trait.Any.html#method.down...) but that just returns an Option so there's nothing special to it.




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

Search: