Destructuring Arrays

You can destructure arrays, tuples, and slices by matching on their elements:

  1. #[rustfmt::skip]
  2. fn main() {
  3. let triple = [0, -2, 3];
  4. println!("Tell me about {triple:?}");
  5. match triple {
  6. [0, y, z] => println!("First is 0, y = {y}, and z = {z}"),
  7. [1, ..] => println!("First is 1 and the rest were ignored"),
  8. _ => println!("All elements were ignored"),
  9. }
  10. }
  • Destructuring of slices of unknown length also works with patterns of fixed length.
  1. fn main() {
  2. inspect(&[0, -2, 3]);
  3. inspect(&[0, -2, 3, 4]);
  4. }
  5. #[rustfmt::skip]
  6. fn inspect(slice: &[i32]) {
  7. println!("Tell me about {slice:?}");
  8. match slice {
  9. &[0, y, z] => println!("First is 0, y = {y}, and z = {z}"),
  10. &[1, ..] => println!("First is 1 and the rest were ignored"),
  11. _ => println!("All elements were ignored"),
  12. }
  13. }
  • Show matching against the tail with patterns [.., b] and [a@..,b]