Structs
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"), } }
This slide should take about 4 minutes.
- Change the literal values in
mto match with the other patterns. - Add a new field to
Movementand make changes to the pattern as needed. - Note how
delta: (x, 0)is a nested pattern.
More to Explore
- Try
match &mand 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 withmatch selfwhen implementing methods on an enum.- The same effect occurs with
match &mut m: the captures become exclusive references.
- The same effect occurs with
- The distinction between a capture and a constant expression can be hard to
spot. Try changing the
10in the first arm to a variable, and see that it subtly doesn’t work. Change it to aconstand see it working again.