7 ms·
Enums in Rust – and why they feel better
- bruce343434 3y agoI always hated the name. You're not enumerating anything. You are picking a variant, encoding a choice. Maybe "sum type" is too "monad", but surely "variant record" or even "variant" would have been a better name.
- hurril 3y agoWhile I agree with you, I can understand going with enum so that they don't scare away the C and C++ crowd with being too fartsy with theoretic stuff.
- MuffinFlavored 3y agothey scared me away when I tried to do from/to u32 and comparing them, etc.
- flohofwoe 3y agoIt is especially confusing for C and C++ coders, because Rust enums are a completely different thing than C enums, which makes the naming choice worse than just inventing a new name. Better names would be "tagged union" (which is spot-on descriptive - because it *is* a union with a tag slapped on - but "tagged_union" of course is a bit unwieldy as keyword) or "variant" (which is the name for that thing in C++ and elsewhere since forever - it's not like Rust invented those tagged-union-thingies, it just added some convenient syntax sugar to the language to deal with them).
- jowea 3y agoMaybe it's because you can use a Rust enum like in C by doing a field-less or unit-only enum?
- hurril 3y agoI agree with you! I dislike the name enum and really like how F# does it. In F#, everything is type and what kind of type you create comes down to the type construction literal you use. ` (* enum ) type 'a Option = Some of 'a | None ` ( struct - well: record. *) type Company = { Name : string Age : int } Fudge. No idea how to format that in HN.
- randomdata 3y agoIn practice, now C developers get to hear from the Rust crowd that C doesn't have enums because what C has is unlike Rust "enums".
- kibwen 3y agoIn early Rust, the keyword was `tag`. In order to improve familiarity with C++ programmers, bikeshedding raged between `enum` and `union` for years before finally landing on the former.
- flohofwoe 3y agoTBH it's kinda funny how they narrowed it down to two options and then went with the "obviously" wrong option (also to get C++ programmers on board, wouldn't the obvious name not be "variant"? I really wonder how that decision making progress looked like :)
- jowea 3y agoUnion did end up meaning another thing that is just like C union and just as unsafe.
- steveklabnik 3y agoDon’t forget rust also has unions. Not using the name “union” for a feature that’s different than unions doesn’t feel “obviously wrong” to me.
- sirwhinesalot 3y agoThe right solution was to make union safe with an opt-in way to make it unsafe IMO.
- steveklabnik 3y agoIn concrete terms, what would that look like?
- metaltyphoon 3y agoSyntax wise Zig does it with union(enum). Union and Enums are both concepts directly related to C and can be used separately too.
- TwentyPosts 3y ago"coproduct type"
- math_dandy 3y agoOCAML uses the terminology “(Polymorphic) Variant” for this kind of thing. Since OCAML is awesome, I consider this a strong precedent.
- dgb23 3y agoThey are tagged unions right? "Enum" is not the worst term here. In fact you are enumerating the variants. It's only slightly misleading. It implies that you're comparing an integer. There is an actual enum backing it to encode the choice (tag), and a union to encode the data (if it has data). Or at least that's what I would expect. "Variant" is used in Rust lingo to name the variants, not the whole type.
- layer8 3y agoSome schema languages call it “choice”.
- hurril 3y ago> A commonly said piece of feedback from someone who's learning Rust as a second language tends to be that enums are far better supported in Rust than any other language. This is nonsense. I doubt that this is common feedback and it is just not correct that it is far better supported in Rust than in any other language. Why would anyone say that? Rust pretty much has support for ADTs, sum types and product types. Just like any modern (functional) language has. Haskell, Scala, F#, OCaml, etc. (And I love rust, write it in my day-to-day as well as on my spare time.)
- ongy 3y agoBecause many people start learning in one of the industry incumbent, not necessarily good by design languages. Java, C, C++, python, Javascript, go... As a second language is a quite different selector than after education in language design or excursions to functional programming.
- pjmlp 3y agoJava enums are also quite powerful versus what C, C++ and C# can do. They are real objects, can have associated data and methods. So if they are surprised by Rust, haven't learnt Java properly
- ongy 3y agoI Haven't used java in ages. Though from a quick search, it's still just scalar/unary values. Rhough one of the better implementations of those. But the big advantage of the more sum type Style enums rust provides is the ability to nest values in them while preserving type safety guarantees. So I still see them as miles better as a language concept.
- fifticon 3y agoerh no, those in java allow you to do just that. It is one of my favorite features of java. In essence, you get to embed multiple synchronized maps inside a java enum (if you want to). All handled 'invisibly' for you.
- rgoulter 3y agoThe term "Newtype" more specifically describes a wrapper around a single type. It's like an alias. It's incorrect to describe an enum with two variants as a 'newtype'. I think the example was misunderstood from https://rust-unofficial.github.io/patterns/patterns/behavioural/newtype.html https://rust-unofficial.github.io/patterns/patterns/behaviou... (which uses Password, but doesn't use an enum with two variants). The use of enums in the example is fine; but it's not a "newtype".
- junon 3y agoMore specifically the newtype pattern is mostly so that you can implement foreign traits on foreign types. You can't normally do this since there's a high risk of duplicate implementations, so by enforcing only local types/foreign traits or foreign types/local traits (and of course local/local types and traits), this duplication doesn't occur - there's only ever one implementation of a trait per type, and the ownership of those implementations is very clear and we'll defined. The newtype pattern simply makes a "local" type that wraps a foreign type, allowing you to implement the foreign trait on the new local type, and forwarding calls of the trait methods to the inner type - all while maintaining the single trait impl and ownership constraints rust imposes. Further, given all of the compiler optimizations that happen, newtypes are effectively free. For those who haven't seen it, this is what newtype looks like: use some::ForeignType; struct LocalType(ForeignType); As the parent comment states, it has nothing to do with enums.
- ReleaseCandidat 3y ago> More specifically the newtype pattern is mostly so that you can implement foreign traits on foreign types. For some definition of "mostly". I use most of my newtypes neither in Rust nor in Haskell to implement traits, but most of the time to declare - newtypes ;) that wrap other (primitive) types.
- stmblast 3y agoHey, author here! Thanks for the feedback. I agree that this could have been worded better - I'll make an adjustment to change this.
- sshine 3y agoBetter enums, but not better ADTs. I didn’t write a lot of compilers in Rust yet, but I find it limiting that you can’t pattern match across a Box<T>, and all ASTs require boxing for recursive references.
- noam_k 3y agoI think what you want is to enable box_patterns[0]. I have no idea why it isn't stable yet. [0] https://doc.rust-lang.org/beta/unstable-book/language-features/box-patterns.html https://doc.rust-lang.org/beta/unstable-book/language-featur...
- ForkMeOnTinder 3y agoI believe it's not stable because it gives std::boxed::Box special treatment in the language. They'd rather find a solution that could work equally well for smart pointers defined outside of std. Box patterns are likely to be superseded by one of these: https://github.com/rust-lang/rust/issues/42640 https://github.com/rust-lang/rust/issues/42640 https://github.com/rust-lang/rust/issues/87121 https://github.com/rust-lang/rust/issues/87121
- Georgelemental 3y agoThe Rust language team wants a more general solution that also works with types like `Arc`, instead of hardcoding a special case for `Box` into the language. This is generally called "deref patterns." But there are tricky open design questions, so the effort is stalled until someone comes up with a proposal addressing them
- drexlspivey 3y ago> I didn’t write a lot of compilers in Rust yet what a pleb
- Rusky 3y agoOften, when you have a compiler-y recursive ADT, you will want to allocate the individual nodes in an arena rather than from the global allocator as with Box. And at that point, you can use references (with the lifetime of the arena) rather than Boxes, and you can pattern match across those. (Note that this doesn't work if your "arena" is just a Vec, which is something people have sort of hijacked the term "arena" for. It needs to be an arena that doesn't reallocate its contents on growth, something like https://docs.rs/bumpalo/latest/bumpalo/ https://docs.rs/bumpalo/latest/bumpalo/, in order to hand out references that live across allocations like this.)
- sirwhinesalot 3y agoOther people have mentioned it in the comments, but they chose the wrong name for these (as did Swift). They're not enums, they're (pick one): - tagged unions - sum types - algebraic datatypes - variants There are some rust packages that transform rust enums into proper enums, the best one being const_table, or my own table_enum. Java got it right except for bundling the data with the Enum object instead of storing it in separate tables. Having said that, I could not be happier that sum types have entered the mainstream.
- vips7L 3y agoJava has sum types now with sealed classes!
- tialaramex 3y agoI think I have much more problem with the idea that table_enum is "proper enums" than with the choice to name Rust's sum types enum. Because Rust is a low bit-banging language, union needs to exist, which I think rules out calling enum "tagged unions" even if that's one possible way to look at the implementation. In a high level language which lacks union types this wouldn't an issue, but Rust is not that language.
- eigenspace 3y agoAn interesting aspect of sum types (what Rust calls enums) is that you can implement them in the language as a library if you have real unions, but not vice-versa. Here's my example of sum types being implemented in julia as a regular package: https://github.com/MasonProtter/SumTypes.jl https://github.com/MasonProtter/SumTypes.jl
- voxl 3y agoI don't find "you can implement tagged unions with regular unions but not vice versa" all that interesting of a statement, since one forces tags on you it's not enlightening that you can't remove them, and with any other structuring mechanism you can add tags back in.
- eigenspace 3y agoYes, that's correct, but I think the way people talk about these things, it's not always clear why that's the case. I.e. I think from that description it's not particularly obvious to me that you can't find sneaky ways of removing the tags. The important thing here is that the tags are fundamental to the subtyping relations. So unless your language is flexible enough to let one redefine what it means to be a subtype, then there's no chance of making unions out of tagged unions. TaggedUnion{A, B} does not have the property that A <: TaggedUnion{A, B}, whereas with regular unions you must have that property, which is a very hard thing to hack into a language after the fact.
- NikkiA 3y agoC++ class enums are perfectly fine, it's just the old style C enums that are awful.
- da39a3ee 3y ago> Other languages like Go do not necessarily have enums, but you can represent enums by using something like this (in Go): This misses the important point that Go lacks pattern matching -- one uses a switch statement instead -- and the Go compiler lacks the ability to check that all branches have been handled in a switch statement. Go's concurrency stuff is beautiful. If Go had sum types / Rust-style enums with pattern matching and handled errors as a Result sum type, then it would be a much nicer language.