Unreachable pattern on enum match


#1

I’m using an enum to store information about a region of memory. The enum has 5 variants, and has #[repr(u8)]. Since it’s possible for memory corruption to invalidate an enum such that it holds an invalid tag, I want to be able to detect this with a _ => {} clause in a match. The compiler complains about this being an unreachable pattern however, since I’m matching on all other variants.

Is there an attribute that allows me to avoid this? If not, I think this should be considered in the language’s design.


#2

Rust enums are not allowed to contain unspecified values (although, I guess with the repr attribute most of the optimizations that would break it are disabled). I think you should use a transparent newtype for these sorts of scenarios, it gives you much more direct control while being almost as ergonomic:

#[repr(transparent)]
#[derive(Copy, Clone, Debug, ...)]
pub struct Data(u8);

impl Data {
    const VARIANT1: Data = Data(0);
    const VARIANT2: Data = Data(1);
    ...

    fn is_valid(&self) -> bool {
        match *self {
            Data::VARIANT1 | Data::VARIANT2 | ... => true,
            _ => false,
         }
    }
}

#3

Thanks very much. I’ll definitely use this.


#4

You could try #[non_exhaustive].


#5

Note that [non_exhaustive] only quiets the unreachability warning (in other crates); it doesn’t let you contain unspecified values.


#6

Thanks, although I’m not certain that’s quite what I’m looking for.