gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:40:40 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>;
}

最佳答案

从 Rust 1.34 开始,我建议实现 TryFrom :

use std::convert::TryFrom;

impl TryFrom<i32> for MyEnum {
type Error = ();

fn try_from(v: i32) -> Result<Self, Self::Error> {
match v {
x if x == MyEnum::A as i32 => Ok(MyEnum::A),
x if x == MyEnum::B as i32 => Ok(MyEnum::B),
x if x == MyEnum::C as i32 => Ok(MyEnum::C),
_ => Err(()),
}
}
}

然后你可以使用TryInto并处理可能的错误:

use std::convert::TryInto;

fn main() {
let x = MyEnum::C as i32;

match x.try_into() {
Ok(MyEnum::A) => println!("a"),
Ok(MyEnum::B) => println!("b"),
Ok(MyEnum::C) => println!("c"),
Err(_) => eprintln!("unknown number"),
}
}

如果您有大量变体,可以使用宏根据枚举的定义自动创建 TryFrom 的并行实现:

macro_rules! back_to_enum {
($(#[$meta:meta])* $vis:vis enum $name:ident {
$($(#[$vmeta:meta])* $vname:ident $(= $val:expr)?,)*
}) => {
$(#[$meta])*
$vis enum $name {
$($(#[$vmeta])* $vname $(= $val)?,)*
}

impl std::convert::TryFrom<i32> for $name {
type Error = ();

fn try_from(v: i32) -> Result<Self, Self::Error> {
match v {
$(x if x == $name::$vname as i32 => Ok($name::$vname),)*
_ => Err(()),
}
}
}
}
}

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

另见:

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

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