Enumerations (enum
) are ways to group together different values, often in a way that’s useful for selectors. They find broad support in almost every popular programming language (and SystemVerilog).
Enums help facilitate pattern matching.
In C/C++
In Rust
We can access the fields of an enum with enum::field
. We’re also able to embed the types inside an enum:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
Notably, Rust has no null value. The standard library does have the “option enum”, which functions similarly:
enum Option<T> {
None,
Some(T),
}
where T
is a generic type. If a value takes on the None
value, we must annotate it for the compiler. By default, all enum variants are public.