如何在Rust中将枚举变体转换为u8?

huangapple go评论78阅读模式
英文:

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&#39;s possible to do it in unsafe, but I&#39;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&lt;u8&gt; is not implemented by MessageType:

#[repr(u8)]
pub enum MessageType {
    Authentication = 1,
    // ...
}

fn main() {
    let n = MessageType::Authentication as u8;
    println!(&quot;{}&quot;, n);
}

huangapple
  • 本文由 发表于 2023年5月21日 16:34:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298971.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定