Guest User

Untitled

a guest
Jul 17th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. // Define data structure
  2. #[derive(Debug)]
  3. enum Shape {
  4. Circle { radius: f64 },
  5. Rectangle { width: f64, height: f64 },
  6. Triangle { base: f64, height: f64 },
  7. }
  8.  
  9. // Add methods
  10. impl Shape {
  11. // "&self" = immutably borrow self - can't mutate values
  12. fn compute_area(&self) -> f64 {
  13. match self {
  14. Shape::Circle{ radius } => radius * 3.14159,
  15. Shape::Rectangle{ width, height } => width * height,
  16. Shape::Triangle{ base, height } => 0.5 * base * height,
  17. // No default required because compiler knows we hit every case!
  18. // If we add another variant to Shape, this match will no longer
  19. // compile. (Try it!)
  20. }
  21. }
  22. }
  23.  
  24. fn main() {
  25. // shortcut macro to make an array literal
  26. // statically typed, but type inference lets you omit them for most local
  27. // vars
  28. let shapes = vec![
  29. Shape::Circle{ radius: 2.0 },
  30. Shape::Rectangle{ width: 3.0, height: 4.0 },
  31. Shape::Triangle{ base: 2.0, height: 3.0 },
  32. ];
  33. // awesome iterator syntax
  34. for shape in shapes.iter() {
  35. // weird printf style syntax... yeah we're still in a systems language
  36. println!("shape = {:?}, area = {:?}", shape, shape.compute_area());
  37. }
  38. }
Add Comment
Please, Sign In to add comment