Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the integer value of an enum?

Tags:

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.

like image 844
Gedweb Avatar asked Oct 26 '15 19:10

Gedweb


People also ask

How do you find the value of an enum number?

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.

Can enum have int values?

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.


1 Answers

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);
}
like image 109
Shepmaster Avatar answered Sep 17 '22 13:09

Shepmaster