2022-12-21 16:36:30 +01:00
|
|
|
# Destructuring Arrays
|
|
|
|
|
|
|
|
You can destructure arrays, tuples, and slices by matching on their elements:
|
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
{{#include ../../third_party/rust-by-example/destructuring-arrays.rs}}
|
|
|
|
```
|
2023-02-06 16:38:01 +00:00
|
|
|
|
2023-02-22 04:41:12 -08:00
|
|
|
|
2023-02-06 16:38:01 +00:00
|
|
|
<details>
|
|
|
|
|
2023-02-09 13:17:33 -08:00
|
|
|
* Destructuring of slices of unknown length also works with patterns of fixed length.
|
2023-02-06 16:38:01 +00:00
|
|
|
|
2023-02-22 04:41:12 -08:00
|
|
|
|
2023-03-11 14:12:32 -08:00
|
|
|
```rust,editable
|
|
|
|
fn main() {
|
|
|
|
inspect(&[0, -2, 3]);
|
|
|
|
inspect(&[0, -2, 3, 4]);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[rustfmt::skip]
|
|
|
|
fn inspect(slice: &[i32]) {
|
|
|
|
println!("Tell me about {slice:?}");
|
|
|
|
match slice {
|
|
|
|
&[0, y, z] => println!("First is 0, y = {y}, and z = {z}"),
|
|
|
|
&[1, ..] => println!("First is 1 and the rest were ignored"),
|
|
|
|
_ => println!("All elements were ignored"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
2023-02-22 04:41:12 -08:00
|
|
|
|
|
|
|
* Create a new pattern using `_` to represent an element.
|
|
|
|
* Add more values to the array.
|
|
|
|
* Point out that how `..` will expand to account for different number of elements.
|
2023-02-09 13:17:33 -08:00
|
|
|
* Show matching against the tail with patterns `[.., b]` and `[a@..,b]`
|
2023-02-22 04:41:12 -08:00
|
|
|
|
2023-02-06 16:38:01 +00:00
|
|
|
</details>
|