Option with Enum Pattern Matching

I don't understand the syntax for pattern matching against an enum type and returning a option of that enum variant. As shown below, I want to get rid of the NONE enum and if the anything is returned that does not match should be an option::none, but I can't figure out the syntax is inside the match block

    #[derive(Clone, Copy, Debug)]
    pub enum Permission {
        NONE = 0,
        R = 1,
        W = 2,
        RW = 3,
        X = 4,
        RX = 5,
        WX = 6,
        RWX = 7,
    }

        #[inline]
        fn permission(&self, byte: usize) -> Option<Permission> {
            match byte.get_bits(0..3) {
                0 => Permission::NONE,
                1 => Permission::R,
                2 => Permission::W,
                3 => Permission::RW,
                4 => Permission::X,
                5 => Permission::RX,
                6 => Permission::WX,
                7 => Permission::RWX,
                _ => None,
            }
        }

You need to wrap the non-None return values in Some:

match byte.get_bits(0..3) {
    0 => Some(Permission::NONE),
    1 => Some(Permission::R),
    // ...
    _ => None,
}

Permission::R (for example) is a value of type Permission, not Option<Permission>, so you can't return it from a function whose signature specifies the return type Option<Permission>.

1 Like

Funny thing is I tried that and ItelliJ yelled at me with red underlines. I put it back after your suggestion and it was perfectly happy. :man_facepalming:

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.