Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. use std::ops::Deref;
  2. use std::fmt::Display;
  3.  
  4. trait Test {
  5. fn test(&self) -> String;
  6. }
  7.  
  8. #[derive(Default)]
  9. struct Child {
  10. a: f32,
  11. b: f32,
  12. }
  13.  
  14. impl Test for Child {
  15. fn test(&self) -> String {
  16. return String::from("test");
  17. }
  18. }
  19.  
  20. impl std::fmt::Display for Child {
  21. fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
  22. // The `f` value implements the `Write` trait, which is what the
  23. // write! macro is expecting. Note that this formatting ignores the
  24. // various flags provided to format strings.
  25. write!(f, "({}, {})", self.a, self.b)
  26. }
  27. }
  28.  
  29. #[derive(Default)]
  30. struct Parent {
  31. ch: Child,
  32. c: f32,
  33. d: f32,
  34. }
  35.  
  36. impl Deref for Parent {
  37. type Target = Child;
  38. fn deref(&self) -> &Child {
  39. &self.ch
  40. }
  41. }
  42.  
  43. fn main() {
  44. let p = Parent{
  45. ch: Child {
  46. a: 1.0,
  47. b: 2.0,
  48. },
  49. c: 3.0,
  50. d: 4.0,
  51. };
  52. println!("{}", p.a);
  53. println!("{}", p.b);
  54. println!("{}", p.c);
  55. println!("{}", p.d);
  56. println!("{}", p.test());
  57. println!("{}", *p);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement