如何将枚举值与整数匹配? [英] How do I match enum values with an integer?

查看:25
本文介绍了如何将枚举值与整数匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以像这样得到一个枚举的整数值:

I can get an integer value of an enums like this:

enum MyEnum {
    A = 1,
    B,
    C,
}

let x = MyEnum::C as i32;

但我似乎无法做到这一点:

but I can't seem to do this:

match x {
    MyEnum::A => {}
    MyEnum::B => {}
    MyEnum::C => {}
    _ => {}
}

如何匹配枚举的值或尝试将 x 转换回 MyEnum?

How can I either match against the values of the enum or try to convert x back to a MyEnum?

我可以看到这样的函数对枚举很有用,但它可能不存在:

I can see a function like this being useful for enums, but it probably doesn't exist:

impl MyEnum {
    fn from<T>(val: &T) -> Option<MyEnum>;
}

推荐答案

您可以派生 FromPrimitive.使用 Rust 2018 简化的导入语法:

You can derive FromPrimitive. Using Rust 2018 simplified imports syntax:

use num_derive::FromPrimitive;    
use num_traits::FromPrimitive;

#[derive(FromPrimitive)]
enum MyEnum {
    A = 1,
    B,
    C,
}

fn main() {
    let x = 2;

    match FromPrimitive::from_i32(x) {
        Some(MyEnum::A) => println!("Got A"),
        Some(MyEnum::B) => println!("Got B"),
        Some(MyEnum::C) => println!("Got C"),
        None            => println!("Couldn't convert {}", x),
    }
}

在您的 Cargo.toml 中:

[dependencies]
num-traits = "0.2"
num-derive = "0.2"

num-derive crate 中的更多详细信息,请参阅 esp.测试中的示例使用.

More details in num-derive crate, see esp. sample uses in tests.

这篇关于如何将枚举值与整数匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆