如何在 Rust 中将 ref 转换为枚举值作为 u16(基本枚举类型)?
How one can cast ref to enum value as u16 (base enum type) in Rust?
鉴于:
#[repr(u16)]
#[derive(PartialEq, Debug, Eq, Hash, Clone)]
pub enum SomeEnum {
SomeValue1 = 1,
SomeValue2 = 1 << 2 | Self::SomeValue1 as u16, // some bitmasks
// ...
}
pub fn some_check(actual_value_ref: &SomeEnum, base_value: SomeEnum) -> bool {
let actual_value_u16 = actual_value_ref.clone() as u16; // how to cast without cloning?
let base_value_u16 = base_value as u16;
actual_value_u16 & base_value_u16 == base_value_u16 // bitmask operation
}
如何在不显式克隆的情况下通过引用为原始获取价值?
克隆 u16
看起来不像是悲剧,但正确的做法是什么?
由于枚举被显式标记为 #[repr(u16)]
为什么编译器不立即执行它?
为了避免显式 clone
ing,我认为 derive(Copy)
对于 SomeEnum
.
应该足够了
鉴于:
#[repr(u16)]
#[derive(PartialEq, Debug, Eq, Hash, Clone)]
pub enum SomeEnum {
SomeValue1 = 1,
SomeValue2 = 1 << 2 | Self::SomeValue1 as u16, // some bitmasks
// ...
}
pub fn some_check(actual_value_ref: &SomeEnum, base_value: SomeEnum) -> bool {
let actual_value_u16 = actual_value_ref.clone() as u16; // how to cast without cloning?
let base_value_u16 = base_value as u16;
actual_value_u16 & base_value_u16 == base_value_u16 // bitmask operation
}
如何在不显式克隆的情况下通过引用为原始获取价值?
克隆 u16
看起来不像是悲剧,但正确的做法是什么?
由于枚举被显式标记为 #[repr(u16)]
为什么编译器不立即执行它?
为了避免显式 clone
ing,我认为 derive(Copy)
对于 SomeEnum
.