logoalt Hacker News

xeubie • yesterday at 9:39 PM • 4 replies • view on HN

Rust enums conflate the tag type with the union type that uses it. These should be separate things. In the example here, you can see that Rust gives no way to represent the tag type `{Human, Cat}`. In Zig there is an enum which is a set of tags, and a union which is backed by that enum and can have fields. It is obviously better to have these as separate concepts rather than conflating them. You often want the kind without the data, and Rust gives you no way to represent it. I'm not sure why I am bothering to rant about this but it's one of my biggest annoyances with the language.


Replies

clownstrikelol • yesterday at 9:47 PM

Sure you can, bringing data along for the ride is optional in Rust. Nothing is forcing you to use it like a tagged union, it’s an optional (but useful) feature.

If you want specific values (integer or otherwise) associated with specific variants (i.e. Human = 1, Cat = 4) you can do that too. Use the #[repr(T)] or impl the From / Into traits yourself.

➕ show 1 reply
ai_ • yesterday at 10:09 PM

The function you seek already exists before you: https://doc.rust-lang.org/std/mem/fn.discriminant.html

Is there anything you can do with separate types for the tag and the union that std::mem::discriminant and pattern matching can't do?

➕ show 3 replies
slopinthebag • yesterday at 9:48 PM

i dont understand what rust doesn't give you that zig does?

➕ show 1 reply