Is there a way I can make a C++ style enumeration with explicit representation type in Rust? Example:
enum class Number: int16_t {
Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine
};
If not, is there another way I can organize variables like that? I am interfacing with an external library, so specifying the type is important. I know I could just do:
type Number = int16_t;
let One: Number = 1;
let Two: Number = 2;
let Three: Number = 3;
But that introduces a lot of redundancy, in my opinion;
Note this question is not a duplicate of Is it possible to wrap C enums in Rust? as it is about wrapping C++, not wrapping C.
In C programming, an enumeration type (also called enum) is a data type that consists of integral constants. To define enums, the enum keyword is used. enum flag {const1, const2, ..., constN}; By default, const1 is 0, const2 is 1 and so on.
Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.
We can also provide the values to the enum name in any order, and the unassigned names will get the default value as the previous one plus one. The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc.
Initializing Enum Variants with Values in Rustlet num = Result::Score(3.14); let bool = Result::Valid(true); Here, we are initializing the enum variants with values inside the bracket. That is, Result::Score(3.14) - initialize the Score variant with the value 3.14.
You can specify a representation for the enum.
#[repr(i16)]
enum Foo {
One = 1,
Two = 2,
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With