The best way to answer this is to find out why you want constants in the enumeration: do you just bind the value to each variant or want each variant to be that value (for example, enum in C or C ++)?
In the first case, it probably makes sense to just leave the enumeration options without data and make a function:
enum MyEnum { A, B, } impl MyEnum { fn value(&self) -> i32 { match *self { MyEnum::A => 123, MyEnum::B => 456, } } }
This approach can be applied many times to associate many individual pieces of information with each option, for example. maybe you need the .name() -> &'static str method .name() -> &'static str .
Alternatively, in the second case, you can assign the values โโof an explicit tag in exactly the same way as C / C ++:
enum MyEnum { A = 123, B = 456, }
It can be match ed in all the same ways, but it can also be added to the integer MyEnum::A as i32 . (Note that calculations like MyEnum::A | MyEnum::B are not automatically legal in Rust: enums have certain values, they are not bit flags.)
source share