src/pattern-matching/destructuring-structs.md
Like tuples, structs can also be destructured by matching:
# // Copyright 2022 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
struct Move {
delta: (i32, i32),
repeat: u32,
}
#[rustfmt::skip]
fn main() {
let m = Move { delta: (10, 0), repeat: 5 };
match m {
Move { delta: (0, 0), .. } => println!("Standing still"),
Move { delta: (x, 0), repeat } => println!("{repeat} step x: {x}"),
Move { delta: (0, y), repeat: 1 } => println!("Single step y: {y}"),
_ => println!("Other move"),
}
}
m to match with the other patterns.Movement and make changes to the pattern as needed.delta: (x, 0) is a nested pattern.match &m and check the type of captures. The pattern syntax remains the
same, but the captures become shared references. This is
match ergonomics
and is often useful with match self when implementing methods on an enum.
match &mut m: the captures become exclusive
references.10 in the first arm to a variable, and see that it
subtly doesn't work. Change it to a const and see it working again.