Get enum discriminant in a derive macro

I'm working on a derive macro for enums which needs access to the discriminant for each variant of the enum. Everything I've found to access it assumes that either your enum has no fields (which doesn't apply here), or you put a #[repr(u*)] attribute on the enum (which I can't do in a derive macro). I also need this discriminant to be a number, not the opaque core::mem::Discriminant<T> type in the standard library.

Right now, I have code in my proc macro which reads the definition of the enum and computes the discriminant of each enum variant. Then, when I need to get the discriminant of a value, the proc macro inserts a match statement on the value, and inserts my manually-computed discriminants in the arms of the match. This works, but adds a lot of code to the macro to track this value that the compiler already has.

Is there a better way of doing this?

You can, however, require its existence (and return an error if there isn't one). This might be the best way to go here, if you need to go only from enum to discriminant and not the other way round.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.