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. }
6. #[rustfmt::skip]
7. fn inspect(slice: &[i32]) {
8. println!("Tell me about {slice:?}");
9. match slice {
10. &[0, y, z] => println!("First is 0, y = {y}, and z = {z}"),
11. &[1, ..] => println!("First is 1 and the rest were ignored"),
12. _ => println!("All elements were ignored"),
13. }
14. }
- Show matching against the tail with patterns
[.., b]and[a@..,b]
