我目前正在使用以下代码将整数转换为枚举类型:
#[rustfmt::skip]
#[derive(Debug, Clone, Copy)]
pub enum Square {
A8, B8, C8, D8, E8, F8, G8, H8,
A7, B7, C7, D7, E7, F7, G7, H7,
A6, B6, C6, D6, E6, F6, G6, H6,
A5, B5, C5, D5, E5, F5, G5, H5,
A4, B4, C4, D4, E4, F4, G4, H4,
A3, B3, C3, D3, E3, F3, G3, H3,
A2, B2, C2, D2, E2, F2, G2, H2,
A1, B1, C1, D1, E1, F1, G1, H1,
}
impl TryFrom<u64> for Square {
type Error = String;
fn try_from(value: u64) -> Result<Self, Self::Error> {
use Square::*;
#[rustfmt::skip]
const LOOKUP: [Square; 64] = [
A8, B8, C8, D8, E8, F8, G8, H8,
A7, B7, C7, D7, E7, F7, G7, H7,
A6, B6, C6, D6, E6, F6, G6, H6,
A5, B5, C5, D5, E5, F5, G5, H5,
A4, B4, C4, D4, E4, F4, G4, H4,
A3, B3, C3, D3, E3, F3, G3, H3,
A2, B2, C2, D2, E2, F2, G2, H2,
A1, B1, C1, D1, E1, F1, G1, H1,
];
LOOKUP
.get(value as usize)
.ok_or_else(|| {
format!(
"index '{}' is not valid, make sure it's in the range '0..64'",
value
)
})
.map(|s| *s)
}
}
我不知道这有多快,但我可能会在未来找到答案。
当然,这种方法的一个缺点是如果枚举值发生更改,则必须在多个地方进行更新。
再读几遍问题后,我发现这并不是问题所要求的。但是我暂时将此答案保留在此处,因为在搜索“rust将整数转换为枚举”时会看到此线程。尽管如此,该答案仍可用于解决问题。只需将x转换为枚举(x.try_into().unwrap()
(实际上你不应该只是简单地解包,而是要处理错误)),然后使用带有枚举变量的正常匹配语句即可。
MyEnum
改为enum MyEnum { A = 1, B, C, Other(i32) }
可能是解决我的问题的更好方案。但我会保留原始问题供其他用户参考(我以前肯定也想过这样做,不知道是出于坏习惯还是缺乏好的替代方案)。 - dhardyenum Codes { A = 1, B, C }; enum MyEnum { Code(Codes), Other(i32) };
的形式。 - dhardy