Unreachable pattern on enum match


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.


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:

#[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,


Thanks very much. I’ll definitely use this.


You could try #[non_exhaustive].


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


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