Enums#
Discriminated unions; each variant can carry data.
enum Shape {
Circle(f64),
Rect { w: f64, h: f64 },
Empty,
}
Construct a variant.
let s = Shape::Circle(2.0);
Match exhaustively; the compiler refuses to compile a non-total match.
match s {
Shape::Circle(r) => println!("area {}", 3.14 * r * r),
Shape::Rect { w, h } => println!("area {}", w * h),
Shape::Empty => println!("nothing"),
}
Two enums in the stdlib do most of the heavy lifting.
enum Option<T> { Some(T), None }
enum Result<T, E> { Ok(T), Err(E) }
Option replaces null; Result replaces exceptions.
See Option and Result.
References#
Option and Result for the two stdlib enums.
Control flow for
matchandif letpattern flow.