Destructuring Structs

You can also destructure structs:

  1. struct Foo {
  2. x: (u32, u32),
  3. y: u32,
  4. }
  5. #[rustfmt::skip]
  6. fn main() {
  7. let foo = Foo { x: (1, 2), y: 3 };
  8. match foo {
  9. Foo { x: (1, b), y } => println!("x.0 = 1, b = {b}, y = {y}"),
  10. Foo { y: 2, x: i } => println!("y = 2, x = {i:?}"),
  11. Foo { y, .. } => println!("y = {y}, other fields were ignored"),
  12. }
  13. }
  • Change the literal values in foo to match with the other patterns.
  • Add a new field to Foo and make changes to the pattern as needed.