简体   繁体   中英

How do I get the integer value of an enum?

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM