snippetrustCritical
How can I create enums with constant values in Rust?
Viewed 0 times
constantwithhowenumsrustcanvaluescreate
Problem
I can do this:
but not this:
I can create the structures for
enum MyEnum {
A(i32),
B(i32),
}but not this:
enum MyEnum {
A(123), // 123 is a constant
B(456), // 456 is a constant
}I can create the structures for
A and B with a single field and then implement that field, but I think there might be an easier way. Is there any?Solution
The best way to answer this is working out why you want constants in an enum: are you associating a value with each variant, or do you want each variant to be that value (like an
For the first case, it probably makes more sense to just leave the enum variants with no data, and make a function:
This approach can be applied many times, to associate many separate pieces of information with each variant, e.g. maybe you want a
For the second case, you can assign explicit integer tag values, just like C/C++:
This can be
enum in C or C++)?For the first case, it probably makes more sense to just leave the enum variants with no data, and make a function:
enum MyEnum {
A,
B,
}
impl MyEnum {
fn value(&self) -> i32 {
match *self {
MyEnum::A => 123,
MyEnum::B => 456,
}
}
}
// call like some_myenum_value.value()This approach can be applied many times, to associate many separate pieces of information with each variant, e.g. maybe you want a
.name() -> &'static str method too. In the future, these functions can even be marked as const functions.For the second case, you can assign explicit integer tag values, just like C/C++:
enum MyEnum {
A = 123,
B = 456,
}This can be
matched on in all the same ways, but can also be cast to an integer MyEnum::A as i32. (Note that computations like MyEnum::A | MyEnum::B are not automatically legal in Rust: enums have specific values, they're not bit-flags.)Code Snippets
enum MyEnum {
A,
B,
}
impl MyEnum {
fn value(&self) -> i32 {
match *self {
MyEnum::A => 123,
MyEnum::B => 456,
}
}
}
// call like some_myenum_value.value()enum MyEnum {
A = 123,
B = 456,
}Context
Stack Overflow Q#36928569, score: 185
Revisions (0)
No revisions yet.