Use the enum keyword with repr attributes and explicit discriminants to create C-style enums in Rust.
Rust does not have C-style enums; it uses enum definitions where variants can optionally hold data or be assigned explicit integer discriminants. To replicate C-style behavior, define an enum with #[repr(u8)] to enforce a specific memory layout and assign explicit values to each variant.
#[repr(u8)]
enum Color {
Red = 0,
Green = 1,
Blue = 2,
}
fn main() {
let c = Color::Red;
let value = c as u8; // 0
}
Rust enums are safer and more powerful than C enums because they can hold data and enforce strict type checking. You can mimic C-style integer enums by explicitly assigning numbers to your variants and specifying the underlying integer type. This ensures your code behaves predictably when interacting with external systems or performing low-level operations.