🔢 Rust Enums
Types
“Normal” enums:
- Can hold enum values
- (start at 0 without specification)
- Can be compared (via derive)
- Can have methods, like structs
Example:
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Measure {
Meter = 1, //optional val
Centimeter = 2
}
// usage
Measure::Meter
Enums with data:
Mirroring struct types:
- tuple variants accept arguments (like 🔢 Rust Tuple-Like Structs)
- e.g.:
x(T, V)→ tuple variant x, taking arguments of Type T, V
- e.g.:
- struct variants can contain named fields (like 🏷️ Rust Named-Fields Structs)
- e.g.:
x { t: T, v: V}→ struct variant x, taking arguments t, v of Type T, V
- e.g.:
- unit variants are fields without data (like 🍽️ Rust Unit-Like Structs)
- e.g.:
x→ unit variant x
- e.g.:
Converting
- Enum to value: cast
- Value to enum: checked cast, or enum_primitive crate
Use case
- simplicity
- no change in the datastructure is expected
- → use struct with 👨🚀 Rust Traits instead