3 ms·
> One thing Rust could really use are anonymous unions (A | B |C instead of E::A(A), E::B(B), E::C(C)). They are to enums what tuple types are to structs. Ceyl
by twic 3y ago
> One thing Rust could really use are anonymous unions (A | B |C instead of E::A(A), E::B(B), E::C(C)). They are to enums what tuple types are to structs.
Ceylon had union types, which is the only place i've seen these: https://github.com/eclipse-archived/ceylon-lang.org/blob/master/documentation/1.3/tour/types.md#union-types https://github.com/eclipse-archived/ceylon-lang.org/blob/mas...
Another thing Rust enums are missing is having each variant be a type. If you have an enum Shape with variants Circle, Rectangle, and Polygon, there is no way to write a function which only takes a Circle. So you end up defining a struct for each case, then making your enum a trivial wrapper round the three structs. You end up with Shape::Circle and Circle, which are different things, and writing code like c.0.radius to get at the fields. It's rather inelegant. So either variants should be types in their own right, or an enum should be defined as a composition of existing types.
- duped 3y agoTypescript and Dart have union types that work this way.
- Expurple 3y agoAlso, Python with type annotations. But it's not a very fair comparison, since objects in Python/TS are all heap-allocated, introspectable and contain rutnime type information. Rust doesn't have any of that by default
- k_g_b_ 3y agoCeylon had a really neat type system - sadly it didn't take off. However before that these types in particular were a feature of OCaml: https://v2.ocaml.org/manual/polyvariant.html https://v2.ocaml.org/manual/polyvariant.html There they're called Polymorphic Variants. Note also the implementation efficiency concerns on that page - given that Rust is a systems language, defaulting to the current sum types instead of set-theoretic unions was a reasonable choice. Having the option to use them natively and without macros (there's some crates) would be nice still when aware of the additional performance overhead.
- gaganyaan 3y agoI haven't been following this closely, so I looked it up and it looks like that's not going to happen for the foreseeable future unfortunately: https://github.com/rust-lang/lang-team/issues/122 https://github.com/rust-lang/lang-team/issues/122 Kind of a shame, but wrapper types work well enough that I understand. It does look like if there was someone with enough resources to make it happen that they'd be receptive to it.