Enums in Rust
Enums define types that can be one of several variants, each possibly carrying data (algebraic data types).
Declaring enums
enum Shape {
Circle { r: f64 },
Rect { w: f64, h: f64 },
Unit,
}
Matching and methods
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle { r } => std::f64::consts::PI * r * r,
Shape::Rect { w, h } => w * h,
Shape::Unit => 0.0,
}
}
}
Option and Result
Idiomatic enums in the standard library.
fn maybe_len(s: Option<&str>) -> usize {
match s { Some(v) => v.len(), None => 0 }
}
fn div(a: i32, b: i32) -> Result<i32, &'static str> {
if b == 0 { Err("/0") } else { Ok(a / b) }
}
Use ? to propagate Result and combinators like map, and_then.
Data-carrying variants and constructors
Construct with variant syntax.
let c = Shape::Circle { r: 2.0 };
Discriminants and repr
You can assign explicit values for C interop:
#[repr(u8)]
enum Color { Red = 1, Green = 2, Blue = 3 }
Summary
- Enums model alternatives with attached data; match exhaustively
- Use
Option/Resultfor absence/errors; leverage?and combinators