๐ข 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