Guest User

Untitled

a guest
Mar 18th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. /* Weird `match` in Rust */
  2.  
  3. #[derive(Debug)]
  4. struct A {
  5. a: u32,
  6. b: String,
  7. c: Option<u32>,
  8. d: Option<String>,
  9. e: Option<u32>,
  10. f: Option<u32>,
  11. }
  12.  
  13. fn main() {
  14.  
  15. let mut u = A {
  16. a: 1,
  17. b: "2".to_owned(),
  18. c: Some(3),
  19. d: Some("4".to_owned()),
  20. e: Some(5),
  21. f: None
  22. };
  23.  
  24. match u {
  25. A { a, b, c: Some(c), d: Some(d), e, f } => {
  26. println!(
  27. "\nDuring match:\n \
  28. u = A {{\n \
  29. a: {},\n \
  30. b: {},\n \
  31. c: Some({}),\n \
  32. d: Some(\"{}\"),\n \
  33. e: {:?},\n \
  34. f: {:?},\n \
  35. }}",
  36. a, b, c, d, e, f
  37. );
  38. }
  39. _ => {}
  40. }
  41.  
  42. println!("\nAfter match:");
  43. println!(" u.a is still here {:?}", u.a);
  44. //println!(" u.b has been moved {:?}", u.b); // error
  45. println!(" u.b has been moved");
  46. println!(" u.c is still here {:?}", u.c);
  47. //println!(" u.d has been moved {:?}", u.d); // error
  48. println!(" u.d has been moved");
  49. println!(" u.e is still here {:?}", u.e);
  50. println!(" u.f is still here {:?}", u.f);
  51.  
  52. /* oh, no, u has gone! */
  53. //println!(" u has been moved {:?}", u); // error
  54. println!(" u has been moved");
  55.  
  56. /* don't cry, u still can update */
  57. u.a += 100;
  58. u.b = "102".to_owned();
  59. match u.c.as_mut() {
  60. Some(v) => *v += 100,
  61. None => {},
  62. }
  63. // error
  64. //match u.d.as_mut() {
  65. // Some(v) => *v = "104".to_owned(),
  66. // None => {},
  67. //}
  68. u.d = Some("104".to_owned());
  69. match u.e.as_mut() {
  70. Some(v) => *v += 100,
  71. None => {},
  72. }
  73. println!(
  74. "\nAfter update:\n \
  75. u = A {{\n \
  76. a: {},\n \
  77. b: {},\n \
  78. c: {:?},\n \
  79. d: {:?},\n \
  80. e: {:?},\n \
  81. f: {:?},\n \
  82. }}",
  83. u.a, u.b, u.c, u.d, u.e, u.f
  84. );
  85.  
  86. /* ah, what an amazing day! u has came back! */
  87. println!("\nu has been updated:\n u = {:?}", u);
  88. }
Add Comment
Please, Sign In to add comment