In Rust, an enum is a type that can represent one of several distinct variants, each of which can hold different data. In memory, values of C-style enums are stored as integers. Occasionally it’s useful to
tell Rust which integers to use:
enum HttpStatus { Ok = 200,
NotModified = 304,
NotFound = 404,
}
Rust has three kinds of enum variant.
1. Variants with no data: correspond to unit-like structs
2. Tuple variants: look like tuple struct
3. Struct variants: have curly braces and named fields
enum RelationshipStatus {
Single,
InARelationship,
ItsComplicated(Option<String>),
ItsExtremelyComplicated {
car: DifferentialEquation,
cdr: EarlyModernistPoem,
},
}
enums with data are stored as a small integer tag, plus enough memory to hold all the fields of the largest variant.
enum RoughTime {
InThePast(TimeUnit, u32),
JustNow,
InTheFuture(TimeUnit, u32),
}
Enums can be generic. Two examples from the standard library are among the most- used data types in the language:
enum Option<T> {
None,
Some(T),
}
enum Result<T, E> {
Ok(T),
Err(E),
}
Since none of those pointer types is allowed to be zero, Rust can represent Option<Box<i32>>
, say, as a single machine word: 0 for None and nonzero for Some pointer.
Enums are ideal for representing values that can be one of several distinct types or possibly none, offering advantages over class hierarchies: they are faster, safer, require less code, and are easier to document. However, enums lack flexibility, as they can't be extended with new variants by end users. To add flexibility, we can use traits to define shared behaviors across different types.