Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Weird `match` in Rust */
- #[derive(Debug)]
- struct A {
- a: u32,
- b: String,
- c: Option<u32>,
- d: Option<String>,
- e: Option<u32>,
- f: Option<u32>,
- }
- fn main() {
- let mut u = A {
- a: 1,
- b: "2".to_owned(),
- c: Some(3),
- d: Some("4".to_owned()),
- e: Some(5),
- f: None
- };
- match u {
- A { a, b, c: Some(c), d: Some(d), e, f } => {
- println!(
- "\nDuring match:\n \
- u = A {{\n \
- a: {},\n \
- b: {},\n \
- c: Some({}),\n \
- d: Some(\"{}\"),\n \
- e: {:?},\n \
- f: {:?},\n \
- }}",
- a, b, c, d, e, f
- );
- }
- _ => {}
- }
- println!("\nAfter match:");
- println!(" u.a is still here {:?}", u.a);
- //println!(" u.b has been moved {:?}", u.b); // error
- println!(" u.b has been moved");
- println!(" u.c is still here {:?}", u.c);
- //println!(" u.d has been moved {:?}", u.d); // error
- println!(" u.d has been moved");
- println!(" u.e is still here {:?}", u.e);
- println!(" u.f is still here {:?}", u.f);
- /* oh, no, u has gone! */
- //println!(" u has been moved {:?}", u); // error
- println!(" u has been moved");
- /* don't cry, u still can update */
- u.a += 100;
- u.b = "102".to_owned();
- match u.c.as_mut() {
- Some(v) => *v += 100,
- None => {},
- }
- // error
- //match u.d.as_mut() {
- // Some(v) => *v = "104".to_owned(),
- // None => {},
- //}
- u.d = Some("104".to_owned());
- match u.e.as_mut() {
- Some(v) => *v += 100,
- None => {},
- }
- println!(
- "\nAfter update:\n \
- u = A {{\n \
- a: {},\n \
- b: {},\n \
- c: {:?},\n \
- d: {:?},\n \
- e: {:?},\n \
- f: {:?},\n \
- }}",
- u.a, u.b, u.c, u.d, u.e, u.f
- );
- /* ah, what an amazing day! u has came back! */
- println!("\nu has been updated:\n u = {:?}", u);
- }
Add Comment
Please, Sign In to add comment