I have an enum:
enum Foo { Bar = 1, }
How do I convert a reference to this enum into an integer to be used in math?
fn f(foo: &Foo) { let f = foo as u8; // error[E0606]: casting `&Foo` as `u8` is invalid let f = foo as &u8; // error[E0605]: non-primitive cast: `&Foo` as `&u8` let f = *foo as u8; // error[E0507]: cannot move out of borrowed content }
Use the IntEnum class from the enum module to convert an enum to an integer in Python. You can use the auto() class if the exact value is unimportant. To get a value of an enum member, use the value attribute on the member.
To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.
Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
*foo as u8
is correct, but you have to implement Copy
because otherwise you would leave behind an invalid reference.
#[derive(Copy, Clone)] enum Foo { Bar = 1, } fn f(foo: &Foo) -> u8 { *foo as u8 }
Since your enum will be a very lightweight object you should pass it around by value anyway, for which you would need Copy
as well.
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