Re:Using enums to represent state in Rust
by duped on Friday September 22, 2023 @04:23PM
(#37617278)
Typescript and Dart have union types that work this way.
Re:Using enums to represent state in Rust
by Expurple on Friday September 22, 2023 @11:48PM
(#37620444)
Also, 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
Re:Using enums to represent state in Rust
by k_g_b_ on Friday September 22, 2023 @05:29PM
(#37618036)
Ceylon 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 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.
Re:Using enums to represent state in Rust
by gaganyaan on Saturday September 23, 2023 @08:37PM
(#37629020)
I 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
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.
Ceylon had union types, which is the only place i've seen these: 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.