Enum (Rust)
An enum defines a type by enumerating its possible variants, where each variant can carry its own data. Rust enums are full algebraic data types — far more powerful than C-style enums.
Rust
An enum value is exactly one of its variants at a time. Unlike enums in many languages, each Rust variant can hold data of different shapes: Message::Quit, Message::Move { x, y }, Message::Write(String). This makes enums perfect for modeling state machines and 'one of several things'.
Enums are most powerful with match, which forces you to handle every variant (the compiler errors if you miss one). The two most important enums in the standard library — Option and Result — are how Rust replaces null and exceptions.
Add methods to an enum with an impl block, just like a struct. Together, structs (AND of fields) and enums (OR of variants) let you express almost any data model precisely.
Syntax
enum Shape {
Circle(f64),
Rect(f64, f64),
}Examples
Rust
enum Shape { Circle(f64), Rect(f64, f64) }
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle(r) => 3.14 * r * r,
Shape::Rect(w, h) => w * h,
}
}
fn main() {
println!("{}", area(&Shape::Rect(2.0, 3.0)));
}Output:
6