简体   繁体   English

如何获取枚举的整数值?

[英]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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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