[英]How one can cast ref to enum value as u16 (base enum type) in Rust?
Given:鉴于:
#[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
}
How one can get value by reference for a primitive without explicit cloning?在没有显式克隆的情况下,如何通过引用获得原语的价值? Cloning of u16
does not look like a tragedy but what's the right way to do it?克隆u16
看起来并不像悲剧,但正确的做法是什么? Since enum is explicitly marked as #[repr(u16)]
why compiler doesn't do it out-of-box?由于 enum 被明确标记为#[repr(u16)]
为什么编译器不开箱即用?
To avoid explicit clone
ing, I think it should suffice to derive(Copy)
for SomeEnum
.为避免显式clone
,我认为为SomeEnum
derive(Copy)
就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.