Sub topic 1
Defining enums and variants
Prerequisites
This chapter assumes basic Rust syntax, structs, tuples, functions, and control flow. You should also understand that ownership determines whether using a value moves it or borrows it.
Defining enums and variants
An enum is a type whose value is exactly one of several named variants. A variant is one possible form of that type. Enums are useful when a value can have different meanings, such as a request that is either Read, Write, or Close.
A variant without data is called a unit variant:
enum Command {
Start,
Stop,
}Command::Start and Command::Stop are values of type Command. The Command:: prefix identifies the enum that owns the variant.
Variants that carry data
Variants can store data. A tuple variant uses unnamed fields, while a struct-like variant uses named fields:
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64),
}This enum can represent three different shapes. A circle stores one named value. A rectangle stores two named values. A triangle stores three values in a fixed order.
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
Shape::Rectangle { width, height } => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
fn main() {
let shape = Shape::Rectangle {
width: 2.0,
height: 3.0,
};
println!("{:.1}", area(&shape));
}Branching with `match`
match compares a value with patterns. A pattern describes a possible shape of a value and can bind the data inside it. In the example, width and height become available inside the rectangle arm.
Letting the compiler check every case
Rust requires a match expression to be exhaustive. Exhaustive means that its arms handle every possible variant. If you add Square to Shape, the compiler rejects area until you add a Square arm. This check prevents a newly added case from being silently ignored.
Exercise
Why does Rust reject a match expression that handles only some enum variants?
Show answer
Because match must be exhaustive, so every possible variant needs a matching arm or an explicitly handled fallback pattern.