gpt4 book ai didi

rust - 如何将枚举值与整数匹配?

转载 作者:行者123 更新时间:2023-12-03 11:31:47 25 4
gpt4 key购买 nike

我可以得到一个枚举的整数值,如下所示:

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

let x = MyEnum::C as i32;

但我似乎无法做到这一点:
match x {
MyEnum::A => {}
MyEnum::B => {}
MyEnum::C => {}
_ => {}
}

我该如何与枚举值匹配或尝试将 x转换回 MyEnum

我可以看到像这样的函数对枚举很有用,但它可能不存在:
impl MyEnum {
fn from<T>(val: &T) -> Option<MyEnum>;
}

最佳答案

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

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。 sample uses in tests

关于rust - 如何将枚举值与整数匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59682720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com