Guest User

Untitled

a guest
Jul 18th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. use std::fmt::Debug;
  2.  
  3. trait Shape {
  4. fn area(&self) -> f32;
  5. }
  6.  
  7. #[derive(Debug)]
  8. struct Square {
  9. length: i32,
  10. }
  11.  
  12. impl Square {
  13. fn new(length: i32) -> Square {
  14. Square { length }
  15. }
  16. }
  17.  
  18. impl Shape for Square {
  19. fn area(&self) -> f32 {
  20. (self.length * self.length) as f32
  21. }
  22. }
  23.  
  24. #[derive(Debug)]
  25. struct Rectangle {
  26. width: i32,
  27. height: i32,
  28. }
  29.  
  30. impl Rectangle {
  31. fn new(width: i32, height: i32) -> Rectangle {
  32. Rectangle { width, height}
  33. }
  34. }
  35.  
  36. impl Shape for Rectangle {
  37. fn area(&self) -> f32 {
  38. (self.width * self.height) as f32
  39. }
  40. }
  41.  
  42. fn print_area<S: Shape+Debug>(shape: &S) {
  43. println!("The area of {:?} is {}",
  44. shape,
  45. shape.area());
  46. }
  47.  
  48. fn main() {
  49. let rect = Rectangle::new(30, 50);
  50. let sqr = Square::new(30);
  51.  
  52. print_area(&rect);
  53. print_area(&sqr);
  54. }
Add Comment
Please, Sign In to add comment