Advertisement
Guest User

Untitled

a guest
May 21st, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. use std::fmt; // Import `fmt`
  2.  
  3. // A structure holding two numbers. `Debug` will be derived so the results can
  4. // be contrasted with `Display`.
  5. #[derive(Debug)]
  6. struct MinMax(i64, i64);
  7.  
  8. // Implement `Display` for `MinMax`.
  9. impl fmt::Display for MinMax {
  10. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  11. // Use `self.number` to refer to each positional data point.
  12. write!(f, "({}, {})", self.0, self.1)
  13. }
  14. }
  15.  
  16. // Define a structure where the fields are nameable for comparison.
  17. #[derive(Debug)]
  18. struct Point2D {
  19. x: f64,
  20. y: f64,
  21. }
  22.  
  23. // Similarly, implement for Point2D
  24. impl fmt::Display for Point2D {
  25. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  26. // Customize so only `x` and `y` are denoted.
  27. write!(f, "x: {}, y: {}", self.x, self.y)
  28. }
  29. }
  30.  
  31. fn main() {
  32. let minmax = MinMax(0, 14);
  33.  
  34. println!("Compare structures:");
  35. println!("Display: {}", minmax);
  36. println!("Debug: {:?}", minmax);
  37.  
  38. let big_range = MinMax(-300, 300);
  39. let small_range = MinMax(-3, 3);
  40.  
  41. println!(
  42. "The big range is {big} and the small is {small}",
  43. small = small_range,
  44. big = big_range
  45. );
  46.  
  47. let point = Point2D { x: 3.3, y: 7.2 };
  48.  
  49. println!("Compare points:");
  50. println!("Display: {}", point);
  51. println!("Debug: {:?}", point);
  52.  
  53. // Error. Both `Debug` and `Display` were implemented but `{:b}`
  54. // requires `fmt::Binary` to be implemented. This will not work.
  55. // println!("What does Point2D look like in binary: {:b}?", point);
  56. }
  57.  
  58. /* Output is:
  59. Compare structures:
  60. Display: (0, 14)
  61. Debug: MinMax(0, 14)
  62. The big range is (-300, 300) and the small is (-3, 3)
  63. Compare points:
  64. Display: x: 3.3, y: 7.2
  65. Debug: Point2D { x: 3.3, y: 7.2 }
  66. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement