TypingKit
← Code

Rust: Enums and match

Written for TypingKit · ~3 min

0 wpm 100% accuracy 100% real accuracy
enum Shape {↵
Circle { radius: f64 },↵
Rect { width: f64, height: f64 },↵
}↵
↵
impl Shape {↵
fn area(&self) -> f64 {↵
match self {↵
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,↵
Shape::Rect { width, height } => width * height,↵
}↵
}↵
}↵
↵
fn main() {↵
let shapes = [Shape::Circle { radius: 1.5 }, Shape::Rect { width: 2.0, height: 3.0 }];↵
let total: f64 = shapes.iter().map(Shape::area).sum();↵
println!("total area: {total:.2}");↵
}