How to convert an enum variant into u8 in Rust? – Rust

by
Ali Hasan
rust-analyzer

Quick Fix: 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", n);
}

The Problem:

In Rust, I have an enum with a #[repr(u8)] attribute, and I want to convert a variant of that enum to a u8. How can I do this without implementing the into() method manually?

Q&A

Convert enum variant into u8 in Rust?

You will have to define the value of each variant manually, and use as instead of .into() for conversion

How can I convert an enum variant into u8 without defining the value of each variant manually?

There is no way to do this without defining the value of each variant manually

Video Explanation:

The following video, titled "0412 -- Rust RFC-compliant URI parser/generator - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

finished the first cut of my port to Rust of my URI library. I still need to work on polishing it up. Notebook page: https://tinyurl.com ...