Structs, Enums, and Matching
Enums
One of Several Shapes
An enum lists variants that can carry data. match reads the active variant and its values.
Program
Play the program to compute the area of a square variant.
enums.rs
Replay: real traced execution (multi-file project)
enum Shape {
Circle(f64),
Square(f64),
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(r) => 3.14 * r * r,
Shape::Square(s) => s * s,
}
}
fn main() {
let shape = Shape::Square(3.0);
let a = area(&shape);
println!("{a}");
}
shape ← (empty)
13fn main() {14 let shap→ (empty)e = Shape::Square(3.0);15 let a = area(&shap(empty)e);16 println!("{a}");a ← 9.0
14 let shape = Shape::Square(3.0);15 let → 9.0a = area(&shap(empty)e);16 println!("{a}");17}output9
Follow the Trace
mainbuildsShape::Square(3.0).area(&shape)receives that square.- The
matchchooses theShape::Square(s)arm. sis3.0, so the return value is9.abecomes9, and the program prints9. | trace point | value | | --- | --- | | shape |Square(3.0)| | matched arm |Shape::Square(s)| |s| 3.0 | | returned area | 9 | | stdout |9|
enum
`enum Shape` defines alternative variants.
variant data
`Square(f64)` carries a value inside the variant.
match variant
`match` binds the inner value, like `s`.
Exercise: enums.rs
Reproduce the output 9, then trace which enum variant and inner value make the square area.