Programmatically convert enum with associated data to repr value

If I have

#[repr(u8)]
enum Foo {
    Bar = 0x01,
    Spamm = 0x02,
}

Then I can get the variant's associated value via

let e = Foo:: Bar;
let val = e as u8;

However, this naive approach does not work when the enum has associated data:

#[repr(u8)]
enum Foo {
    Bar(u16) = 0x01,
    Spamm(String) = 0x02,
}

Is there a native way to get the associated tag value of the enum, short of using a macro or third-party library?

Note to myself: Reading helps!

Would be good to have a safe way to do it though.

Yeah, I'd prefer that as well. In order to prevent a discrepancy between repr(T) and the casting in id(), I guess one could introduce a derive proc macro, that both sets repr(T) and implements id() -> T.
However, I guess you'd need a macro for each possible type, because afaik procedural macros cannot be parameterized. So there's no way to have #[derive(Identify(u8))], but you'd then have #[derive(IdentifyU8)] instead.

See conversations like https://github.com/rust-lang/rfcs/pull/3607 for things that might exist in the future.

(I really need to get back to updating that :grimacing:)

2 Likes

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.