It is possible to write constructions like this:
enum Number {
One = 1,
Two = 2,
Three = 3,
Four = 4,
}
but for what purpose? I can't find any method to get the value of an enum variant.
Get the value of an Enum 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.
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.
You get the value by casting the enum variant to an integral type:
enum Thing {
A = 1,
B = 2,
}
fn main() {
println!("{}", Thing::A as u8);
println!("{}", Thing::B as u8);
}
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