logoalt Hacker News

ai_ • yesterday at 10:09 PM • 3 replies • view on HN

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?


Replies

Jtsummers • yesterday at 10:47 PM

As someone who hasn't used Rust enough, and not knowing Zig but it appears Zig does something similar to Ada which I do know, how would you use the same discriminant across multiple Rust enums and guarantee that you implemented variants for each discriminant value?

In Ada, if I use an enum (carrying the example from a link I used in a cousin comment):

  type Expr_Kind_Type is (Bin_Op_Plus,
                           Bin_Op_Minus,
                           Num);
https://learn.adacore.com/courses/intro-to-ada/chapters/more...

Variant records using this enum have to implement the variant for each element of the enum. If I, for some reason, have multiple records using the same discriminant I can know that each one implements it for each value of the discriminant. Does Rust have a way to synchronize your enums similar to that?

➕ show 2 replies
tcfhgj • yesterday at 11:27 PM

yeah, but fortunately strum exists.

I have found it quite useful to be able to generate a dedicated SomeEnumDiscriminants enum for SomeEnum, using the following derive:

https://docs.rs/strum/latest/strum/derive.EnumDiscriminants....

xeubie • yesterday at 10:22 PM

Yes, there is something you can do with separate types. You can name a variant without having a value of it. `discriminant` only works on an existing value, so to refer to "cats" you'd have to build a dummy `Cat`, and the result is opaque. You can't match on it, iterate over it, or create one from a byte you parsed off the wire. This is so obviously worse, I can't believe you bothered to ask.

➕ show 1 reply