Guest User

Untitled

a guest
Dec 15th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. use std::fmt;
  2.  
  3. enum ContainedType {
  4. SomeType,
  5. OtherType,
  6. }
  7.  
  8. struct OurObject {
  9. contains: ContainedType,
  10. }
  11.  
  12. impl OurObject {
  13. pub fn get_type(self) -> ContainedType {
  14. self.contains
  15. }
  16. }
  17.  
  18. trait MeaninglessNumeric {
  19. fn numeric(&self) -> i32;
  20. }
  21.  
  22. struct AType {
  23. value: i32,
  24. }
  25.  
  26.  
  27. impl fmt::Debug for AType {
  28. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  29. write!(f, "AType {}", self.value)
  30. }
  31. }
  32.  
  33. impl MeaninglessNumeric for AType {
  34. fn numeric(&self) -> i32 {
  35. self.value
  36. }
  37. }
  38.  
  39. struct BType {
  40. contents: String
  41. }
  42.  
  43. impl fmt::Debug for BType {
  44. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  45. write!(f, "BType {}", self.contents)
  46. }
  47. }
  48.  
  49. impl MeaninglessNumeric for BType {
  50. fn numeric(&self) -> i32 {
  51. self.contents.len() as i32
  52. }
  53. }
  54.  
  55. // These are very contrived examples. In the real world, the values are not
  56. // created out of thin air but are extracted from data in OurObject.
  57.  
  58. fn example1(obj: OurObject) {
  59. match obj.get_type() {
  60. ContainedType::SomeType => println!("{:?}", AType { value: 5 }),
  61. ContainedType::OtherType => println!("{:?}", BType { contents: "hello, world".to_string() }),
  62. }
  63. }
  64.  
  65. fn example2(obj: OurObject) {
  66. match obj.get_type() {
  67. ContainedType::SomeType => println!("{}", AType { value: 5 }.numeric()),
  68. ContainedType::OtherType => println!("{}", BType { contents: "hello, world".to_string() }.numeric()),
  69. }
  70. }
  71.  
  72. trait ObjectTrait {
  73. fn example1(&self);
  74. fn example2(&self);
  75. }
  76.  
  77. struct Object2<E> {
  78. thing : E
  79. }
  80.  
  81. impl<E: fmt::Debug + MeaninglessNumeric> ObjectTrait for Object2<E> {
  82. fn example1(&self){
  83. println!("{:?}",self.thing);
  84. }
  85. fn example2(&self){
  86. println!("{}",self.thing.numeric());
  87. }
  88. }
  89.  
  90. fn example3(o : &ObjectTrait){
  91. o.example1();
  92. }
  93. fn example4(o : &ObjectTrait){
  94. o.example2();
  95. }
  96.  
  97. fn main() {
  98. let obj1 = OurObject { contains: ContainedType::SomeType };
  99. let obj2 = OurObject { contains: ContainedType::OtherType };
  100. let obj3 = Object2 {thing : AType{value:5}};
  101. let obj4 = Object2 {thing : BType{contents:"Hello, World".to_string()}};
  102.  
  103. example1(obj1);
  104. example2(obj2);
  105. example3(&obj3);
  106. example4(&obj4);
  107. }
Add Comment
Please, Sign In to add comment