Question Details

No question body available.

Tags

rust

Answers (2)

Accepted Answer Available
Accepted Answer
January 10, 2026 Score: 3 Rep: 2,577 Quality: High Completeness: 50%

Just convert the enum value to a u16, then compare as an integer:

let start: u16 = ;
if start != Packets::StartCode as u16 {
    // ...
}

You can't normally compare two values of different types directly, but you can convert them into the same type and then compare. Converting an integer into an enum is usually quite difficult (and is easiest to do using third-party crates), but converting this sort of enum into an integer is just a case of using as, e.g. as u16 in this case.

January 10, 2026 Score: 3 Rep: 144,732 Quality: Medium Completeness: 80%

I suggest you parse the incoming value from the device as soon as possible and use that internally:

enum ProtocolError { UnknownPacketType(u16), }

impl TryFrom for Packets { type Error = ProtocolError; fn tryfrom(value: u16) -> Result { match value { 0xEF01 => Ok(Self::StartCode), 0x01 => Ok(Self::CommandPacket), ..., => Err(ProtocolError::UknownPacketType(value)) } } }

you can then implement Eq for your Packets type and compare the incoming value

#[derive(Copy, Clone, PartialEq, Eq)] #[repr(u16)] pub enum Packets { ... }

let start: u16 = match Packets::tryfrom(start) { Ok(packet) => { if packet == Packets::StartCode { ... } }, Err(e) => { // handle error } }

implementing TryFrom manually is pretty tedious so you can use a crate like FromRepr to simplify it e.g.

#[derive(Copy, Clone, PartialEq, Eq, FromRepr)] #[repr(u16)] pub enum Packets { ... } let start: u16 = match Packets::from
repr(start) { }