fork download
  1. use std::io::stdin;
  2. use std::io::BufRead;
  3. use std::io::BufReader;
  4. use std::boxed::Box;
  5. use std::vec::Vec;
  6.  
  7. mod figures {
  8.  
  9. pub trait Figure {
  10. fn area(&self) -> f64;
  11. fn printName(&self) {
  12. print!("Figure = {} ", self.name());
  13. }
  14. fn name(&self) -> &'static str;
  15. }
  16.  
  17. pub struct Rectangle {
  18. w: f64,
  19. h: f64,
  20. }
  21.  
  22. impl Rectangle {
  23. pub fn new(width: f64, height: f64) -> Rectangle {
  24. Rectangle { w: width, h: height }
  25. }
  26. }
  27.  
  28. impl Figure for Rectangle {
  29. fn name(&self) -> &'static str {
  30. "Rectangle"
  31. }
  32. fn area(&self) -> f64 {
  33. self.h * self.w
  34. }
  35. }
  36.  
  37. pub struct Square {
  38. rectangle: Rectangle,
  39. }
  40.  
  41. impl Square {
  42. pub fn new(size: f64) -> Square {
  43. Square { rectangle: Rectangle { w: size, h: size } }
  44. }
  45. }
  46.  
  47. impl Figure for Square {
  48. fn name(&self) -> &'static str {
  49. "Square"
  50. }
  51. fn area(&self) -> f64 {
  52. self.rectangle.area()
  53. }
  54. }
  55.  
  56. pub struct Ellipse {
  57. rectangle: Rectangle,
  58. }
  59.  
  60. impl Ellipse {
  61. pub fn new(a: f64, b: f64) -> Ellipse {
  62. Ellipse { rectangle: Rectangle { w: a, h: b } }
  63. }
  64. }
  65.  
  66. impl Figure for Ellipse {
  67. fn name(&self) -> &'static str {
  68. "Ellipse"
  69. }
  70. fn area(&self) -> f64 {
  71. self.rectangle.area() * 3.1415
  72. }
  73. }
  74. }
  75.  
  76. fn main() {
  77. use figures::{Figure, Rectangle, Square, Ellipse};
  78. let mut v: Vec<Box<Figure>> = Vec::with_capacity(4);
  79. v.push(Box::new(Rectangle::new(2.0, 3.0)));
  80. v.push(Box::new(Square::new(4.0)));
  81. v.push(Box::new(Ellipse::new(2.0, 3.0)));
  82. for i in &v {
  83. i.printName();
  84. println!(", area: {}", i.area());
  85. }
  86. }
  87.  
Success #stdin #stdout 0s 4520KB
stdin
Standard input is empty
stdout
Figure = Rectangle , area: 6
Figure = Square , area: 16
Figure = Ellipse , area: 18.849