Guest User

Untitled

a guest
Mar 17th, 2018
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. // Important: traits are of unknown size, and so must be passed around
  2. // as a reference
  3. trait Shape {
  4. fn area(&self) -> f32;
  5. }
  6. // As seen here.
  7. struct ShapeCollection<'a> {
  8. shapes: Vec<&'a Shape>
  9. }
  10.  
  11. // This function needs to return a ShapeCollection, but since the
  12. // data structure requires references to work, it seems impossible!
  13. fn make_shapes<'a>(needRectangle: bool, multiplier: f32) -> ShapeCollection<'a> {
  14. let rect = Rectangle {
  15. width: 42.0 * multiplier,
  16. height: 24.0 * multiplier
  17. };
  18. let circle = Circle {
  19. radius: 42.0 * multiplier
  20. };
  21.  
  22. match needRectangle {
  23. true => ShapeCollection {
  24. shapes: vec![&rect, &circle]
  25. },
  26. false => ShapeCollection {
  27. shapes: vec![&circle]
  28. },
  29. }
  30. }
  31. // ^ This function won't compile because rect and circle do not
  32. // life long enough, and the compiler dies at this point
  33.  
  34. // Impls if you're interested / want to compile, but not that important
  35. struct Rectangle {
  36. width: f32,
  37. height: f32
  38. }
  39. impl Shape for Rectangle {
  40. fn area(&self) -> f32 {
  41. self.width * self.height
  42. }
  43. }
  44. struct Circle {
  45. radius: f32
  46. }
  47. impl Shape for Circle {
  48. fn area(&self) -> f32 {
  49. (std::f32::consts::PI * self.radius).powf(2f32)
  50. }
  51. }
  52.  
  53. enum Shape2 {
  54. Rectangle { width: f32, height: f32 },
  55. Circle { radius: f32 }
  56. }
  57. fn area(shape: Shape2) -> f32 {
  58. match shape {
  59. Shape2::Rectangle {width, height} => width * height,
  60. Shape2::Circle {radius} => (std::f32::consts::PI * radius).powf(2f32)
  61. }
  62. }
  63. struct Shape2Collection {
  64. shapes: Vec<Shape2>
  65. }
  66.  
  67. fn make_shapes2(needRectangle: bool, multiplier: f32) -> Shape2Collection {
  68. let rect = Shape2::Rectangle {
  69. width: 42.0 * multiplier,
  70. height: 24.0 * multiplier
  71. };
  72. let circle = Shape2::Circle {
  73. radius: 42.0 * multiplier
  74. };
  75.  
  76. match needRectangle {
  77. true => Shape2Collection {
  78. shapes: vec![rect, circle]
  79. },
  80. false => Shape2Collection {
  81. shapes: vec![circle]
  82. },
  83. }
  84. }
Add Comment
Please, Sign In to add comment