Rust
Beginner
1 min read
Defining Enums and Match Expressions
Example
#[derive(Debug)]
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64), // three side lengths
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
Shape::Rectangle { width, height } => width * height,
Shape::Triangle(a, b, c) => {
// Heron's formula
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
fn name(&self) -> &'static str {
match self {
Shape::Circle { .. } => "circle",
Shape::Rectangle { .. } => "rectangle",
Shape::Triangle(..) => "triangle",
}
}
}
fn main() {
let shapes: Vec<Shape> = vec![
Shape::Circle { radius: 5.0 },
Shape::Rectangle { width: 4.0, height: 6.0 },
Shape::Triangle(3.0, 4.0, 5.0),
];
for s in &shapes {
println!("{}: area = {:.4}", s.name(), s.area());
}
// Match with a guard
let n = 7i32;
let desc = match n {
i if i < 0 => "negative",
0 => "zero",
i if i % 2 == 0 => "positive even",
_ => "positive odd",
};
println!("{n} is {desc}");
}