Skip to content

Instantly share code, notes, and snippets.

@nebelgrau77
Last active April 11, 2021 10:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nebelgrau77/929e41a3e2883915899bcddcd86f6509 to your computer and use it in GitHub Desktop.
Save nebelgrau77/929e41a3e2883915899bcddcd86f6509 to your computer and use it in GitHub Desktop.
Struct vs enum to hold register addresses in a Rust hardware driver

What are, if any, pros or cons of using a struct vs using an enum to hold register addresses for a device driver? Different authors of such drivers seem to approach it differently. At first sight the struct seems to make more sense, as there is no need to add the function that will return actual u8 values required by the functions. Is there some good reason to use enum here?

struct Register;
impl Register {
    const CTRL_STATUS_2     : u8 = 0x01;
}

/// Clear the timer flag.
pub fn clear_timer_flag(&mut self) -> Result<(), Error<E>> {
    self.clear_register_bit_flag(Register::CTRL_STATUS_2, 0b0001_0000)
}

vs this approach:

pub enum Register {    
    CTRL_STATUS_2 = 0x01,    
}

impl Register {
    pub fn addr(self) -> u8 {
        self as u8
    }
}

/// Clear the timer flag.
pub fn clear_timer_flag(&mut self) -> Result<(), Error<E>> {
    self.clear_register_bit_flag(Register::CTRL_STATUS_2.addr(), 0b0001_0000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment