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

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

How to convert an enum variant into u8 in Rust?

问题

  1. 我想这样做。
  2. ```rust
  3. #[repr(u8)]
  4. pub enum MessageType {
  5. 认证,
  6. // ...
  7. }
  8. fn main() {
  9. let message_type = MessageType::认证;
  10. let binary_representation: u8 = message_type.into();
  11. }

我觉得我不得不手动实现 into。

有没有人有一个可以使用这个表示来转换我的类型的解决方案。

我觉得可以在不安全的情况下做到,但我宁愿不这样做。

这仍然可能对文化有趣。

  1. <details>
  2. <summary>英文:</summary>
  3. 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();
}

  1. I see myself obliged to implement into by hand.
  2. Does anyone have a solution that would use the representation to convert my type.
  3. I think it&#39;s possible to do it in unsafe, but I&#39;d rather not.
  4. It could still be interesting for culture.
  5. </details>
  6. # 答案1
  7. **得分**: 2
  8. 你需要手动定义每个变体的值,并在转换时使用 `as` 而不是 `.into()`,因为 `Into<u8>` 没有由 `MessageType` 实现:
  9. ```rust
  10. #[repr(u8)]
  11. pub enum MessageType {
  12. Authentication = 1,
  13. // ...
  14. }
  15. fn main() {
  16. let n = MessageType::Authentication as u8;
  17. println!("{}", n);
  18. }
英文:

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:

  1. #[repr(u8)]
  2. pub enum MessageType {
  3. Authentication = 1,
  4. // ...
  5. }
  6. fn main() {
  7. let n = MessageType::Authentication as u8;
  8. println!(&quot;{}&quot;, n);
  9. }

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:

确定