Guest User

Untitled

a guest
Jun 22nd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. #[derive(Debug)]
  2. struct MotorImpl {
  3. speed: u8,
  4. }
  5.  
  6. #[derive(Debug)]
  7. struct SpecializedMotorImpl(MotorImpl);
  8.  
  9. impl MotorImpl {
  10. fn new() -> MotorImpl {
  11. MotorImpl { speed: 0 }
  12. }
  13. }
  14.  
  15. trait Motor {
  16. fn run(&mut self) {
  17. self.set_speed(1);
  18. }
  19. fn stop(&mut self) {
  20. self.set_speed(0);
  21. }
  22.  
  23. fn set_speed(&mut self, speed: u8);
  24. }
  25.  
  26. impl Motor for MotorImpl {
  27. fn set_speed(&mut self, speed: u8) {
  28. self.speed = speed
  29. }
  30. }
  31.  
  32. trait SpecializedMotor: Motor {
  33. fn run_fast(&mut self) {
  34. self.set_speed(2);
  35. }
  36. }
  37.  
  38. impl Motor for SpecializedMotorImpl {
  39. fn set_speed(&mut self, speed: u8) {
  40. self.0.set_speed(speed)
  41. }
  42. }
  43.  
  44. impl SpecializedMotor for SpecializedMotorImpl {}
  45.  
  46. fn main() {
  47. let mut motor = MotorImpl::new();
  48. let mut specialized_motor = SpecializedMotorImpl(MotorImpl::new());
  49.  
  50. println!("{:?}", motor);
  51. motor.run();
  52. println!("{:?}", motor);
  53. motor.stop();
  54. println!("{:?}", motor);
  55.  
  56. println!("{:?}", specialized_motor);
  57. specialized_motor.run();
  58. println!("{:?}", specialized_motor);
  59. specialized_motor.stop();
  60. println!("{:?}", specialized_motor);
  61. specialized_motor.run_fast();
  62. println!("{:?}", specialized_motor);
  63. specialized_motor.stop();
  64. println!("{:?}", specialized_motor);
  65. }
Add Comment
Please, Sign In to add comment