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
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}");
}
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`.