Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Mapping for Enums

Enums are mapped to trivial enums in Rust. Each generated enum has a const constructor, and should implement the Default trait.

For convenience, each enum also implements std::str::FromStr and std::fmt::Display, for respectively converting the enum from and to its string representation. The Display implementation automatically provides ToString.

Enums are always trivial (they consist only of discriminant values) and always have total order, so they derive Copy, Eq, Ord, and Hash in addition to the base traits. See Derived Traits for details on trait derivation rules.

Representation

The #[repr] attribute specifies the underlying integer type used to store the enum discriminant. This is determined by the @bit_bound annotation in IDL:

@bit_boundRust #[repr]
8u8
16u16
32 (default)u32
64u64

If @bit_bound is not specified, the default is 32 bits (u32).

Example

@bit_bound(32)
enum MyEnum {
    ONE,
    TWO,
    @value(9) NINE
};
#![allow(unused)]
fn main() {
#[repr(u32)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum MyEnum {
    One,
    Two,
    Nine = 9,
}

impl MyEnum {
    #[must_use]
    pub const fn new() -> Self {
        MyEnum::One
    }
}

impl FromStr for MyEnum {
    // ...
}

impl Display for MyEnum {
    // ...
}

impl Default for MyEnum {
    fn default() -> Self {
        Self::new()
    }
}
}