fptech20
fptech20

Reputation: 173

rust enum with internal tuple and specific values

Is there any way to specify specific values to different enum variants and an internal tuple to hold additional variables? What I want is something like this:

#[repr(u8)]
enum Test {
a(String) = 0x01,
b(u32, u32) = 0x32,
c([u8;3]) = 0x44,
...
}

both of these are valid:

#[repr(u8)]
enum Test {
a(String),
b(u32, u32),
c([u8;3]),
...
}
#[repr(u8)]
enum Test1 {
a = 0x01,
b = 0x32,
c = 0x44,
...
}

If not, then what is the best way of achieving something similar?

Thanks!

Upvotes: 1

Views: 641

Answers (2)

Kevin Reid
Kevin Reid

Reputation: 43852

The feature you're looking for is already implemented, and known as arbitrary_enum_discriminant, but not yet released in a stable version.

You can wait until Rust 1.56.0 is released, which is expected to be October 21st 2021, or use the unstable nightly build of compiler.

Upvotes: 1

Kartheek Tammana
Kartheek Tammana

Reputation: 80

You could use enum-map, or you could just do something like this:

impl Test {
    #[inline]
    fn get_val(&self) -> u8 {
        match self {
            Self::a(_) => 0x01,
            Self::b(_, _) => 0x32,
            Self::c(_) => 0x44,
        }
    }
}

Upvotes: 2

Related Questions