Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Define data structure
- #[derive(Debug)]
- enum Shape {
- Circle { radius: f64 },
- Rectangle { width: f64, height: f64 },
- Triangle { base: f64, height: f64 },
- }
- // Add methods
- impl Shape {
- // "&self" = immutably borrow self - can't mutate values
- fn compute_area(&self) -> f64 {
- match self {
- Shape::Circle{ radius } => radius * 3.14159,
- Shape::Rectangle{ width, height } => width * height,
- Shape::Triangle{ base, height } => 0.5 * base * height,
- // No default required because compiler knows we hit every case!
- // If we add another variant to Shape, this match will no longer
- // compile. (Try it!)
- }
- }
- }
- fn main() {
- // shortcut macro to make an array literal
- // statically typed, but type inference lets you omit them for most local
- // vars
- let shapes = vec![
- Shape::Circle{ radius: 2.0 },
- Shape::Rectangle{ width: 3.0, height: 4.0 },
- Shape::Triangle{ base: 2.0, height: 3.0 },
- ];
- // awesome iterator syntax
- for shape in shapes.iter() {
- // weird printf style syntax... yeah we're still in a systems language
- println!("shape = {:?}, area = {:?}", shape, shape.compute_area());
- }
- }
Add Comment
Please, Sign In to add comment