Fixed Enumerations in Rust

I can do it:

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 structures for A and B with one field and then implement this field, but I think it might be easier. Whether there is a?

+6
source share
2 answers

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, } } } // call like some_myenum_value.value() 

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.)

+21
source

People looking at this can stumble upon the introduction and obsolescence of FromPrimitive . A possible replacement, which may also be useful here, is enum_primitive . It allows you to use C-shaped enumerations and transfer them between digital and logical representation:

 #[macro_use] extern crate enum_primitive; extern crate num; use num::FromPrimitive; enum_from_primitive! { #[derive(Debug, PartialEq)] enum FooBar { Foo = 17, Bar = 42, Baz, } } fn main() { assert_eq!(FooBar::from_i32(17), Some(FooBar::Foo)); assert_eq!(FooBar::from_i32(42), Some(FooBar::Bar)); assert_eq!(FooBar::from_i32(43), Some(FooBar::Baz)); assert_eq!(FooBar::from_i32(91), None); } 
+2
source

All Articles