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