英文:
How to convert an enum variant into u8 in Rust?
问题
我想这样做。
```rust
#[repr(u8)]
pub enum MessageType {
认证,
// ...
}
fn main() {
let message_type = MessageType::认证;
let binary_representation: u8 = message_type.into();
}
我觉得我不得不手动实现 into。
有没有人有一个可以使用这个表示来转换我的类型的解决方案。
我觉得可以在不安全的情况下做到,但我宁愿不这样做。
这仍然可能对文化有趣。
<details>
<summary>英文:</summary>
I would like to do that.
#[repr(u8)]
pub enum MessageType {
Authentification,
// ...
}
fn main() {
let message_type = MessageType::Authentification;
let binary_representation: u8 = message_type.into();
}
I see myself obliged to implement into by hand.
Does anyone have a solution that would use the representation to convert my type.
I think it's possible to do it in unsafe, but I'd rather not.
It could still be interesting for culture.
</details>
# 答案1
**得分**: 2
你需要手动定义每个变体的值,并在转换时使用 `as` 而不是 `.into()`,因为 `Into<u8>` 没有由 `MessageType` 实现:
```rust
#[repr(u8)]
pub enum MessageType {
Authentication = 1,
// ...
}
fn main() {
let n = MessageType::Authentication as u8;
println!("{}", n);
}
英文:
You will have to define the value of each variant manually, and use as
instead of .into()
for conversion, since Into<u8>
is not implemented by MessageType
:
#[repr(u8)]
pub enum MessageType {
Authentication = 1,
// ...
}
fn main() {
let n = MessageType::Authentication as u8;
println!("{}", n);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论