Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. #![feature(specialization)]
  2. use ::std::*;
  3. type Str = borrow::Cow<'static, str>;
  4.  
  5. trait Point {
  6. fn magnitude (self: &'_ Self) -> f64;
  7. fn name (self: &'_ Self) -> &'_ str;
  8. }
  9.  
  10. #[derive(Debug, Clone, Copy)]
  11. struct BasePoint {
  12. x: f64,
  13. y: f64,
  14. }
  15.  
  16. impl Point for BasePoint {
  17. fn magnitude (self: &'_ Self) -> f64
  18. {
  19. let &BasePoint { x, y } = self;
  20. f64::sqrt(x * x + y * y)
  21. }
  22.  
  23. #[inline]
  24. fn name (self: &'_ Self) -> &'_ str {
  25. "Point"
  26. }
  27. }
  28.  
  29. trait SubPoint {
  30. type Super : Point;
  31.  
  32. #[allow(non_snake_case)]
  33. fn upcast_Point (self: &'_ Self) -> &'_ Self::Super;
  34. }
  35.  
  36. impl<P : SubPoint> Point for P {
  37. #[inline]
  38. default
  39. fn magnitude (self: &'_ Self) -> f64
  40. {
  41. self.upcast_Point().magnitude()
  42. }
  43.  
  44. #[inline]
  45. default
  46. fn name (self: &'_ Self) -> &'_ str
  47. {
  48. self.upcast_Point().name()
  49. }
  50. }
  51.  
  52. #[derive(Debug, Clone)]
  53. struct NamedPoint {
  54. point: BasePoint,
  55. name: Str,
  56. }
  57.  
  58. /// derives non-overriden methods
  59. impl SubPoint for NamedPoint {
  60. type Super = BasePoint;
  61.  
  62. #[inline]
  63. fn upcast_Point (self: &'_ Self) -> &'_ Self::Super { &self.point }
  64. }
  65.  
  66. /// overriden methods
  67. impl Point for NamedPoint {
  68. #[inline]
  69. fn name (self: &'_ Self) -> &'_ str { &*self.name }
  70. }
  71.  
  72. fn handle_point (point: &'_ impl Point)
  73. {
  74. println!("{} has a magnitude of {}", point.name(), point.magnitude());
  75. }
  76.  
  77. fn main ()
  78. {
  79. let point = &NamedPoint {
  80. point: BasePoint { x: 3., y: 4. },
  81. name: "Foo".into(),
  82. };
  83. handle_point(point);
  84. handle_point(point.upcast_Point());
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement