Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. enum Foo {
  2. A(Box<u8>),
  3. B(Box<u8>)
  4. }
  5.  
  6. #[derive(Copy, Clone, Debug)]
  7. enum SwitchMode {
  8. A,
  9. B
  10. }
  11.  
  12. impl Foo {
  13. fn update(&mut self) -> SwitchMode {
  14. // run the update
  15. match self {
  16. Foo::A(_) => { return SwitchMode::B }
  17. Foo::B(_) => { return SwitchMode::A }
  18. }
  19. }
  20.  
  21. fn switch_mode(self, mode: SwitchMode) -> Foo {
  22. // change the mode
  23. #[allow(unreachable_patterns)]
  24. match (self, mode) {
  25. (Foo::A(v), SwitchMode::A) => {
  26. Foo::A(v)
  27. }
  28. (Foo::B(v), SwitchMode::A) => {
  29. Foo::A(v)
  30. }
  31.  
  32. (Foo::B(v), SwitchMode::B) => {
  33. Foo::B(v)
  34. }
  35. (Foo::A(v), SwitchMode::B) => {
  36. Foo::B(v)
  37. }
  38. _ => panic!("Invalid state transition")
  39. }
  40. }
  41.  
  42. fn debug(&mut self) {
  43. // debugging
  44. match &self {
  45. Foo::A(v) => println!("Foo::A: {:?}", v),
  46. Foo::B(v) => println!("Foo::B: {:?}", v)
  47. }
  48. }
  49. }
  50.  
  51. fn main() {
  52. println!("GUD NUF");
  53.  
  54. let mut f = Foo::A(Box::new(3));
  55. let mode = f.update();
  56. f.debug();
  57. f = f.switch_mode(mode);
  58. f.debug();
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement