|
| 1 | +# arrays/slices |
| 2 | + |
| 3 | +In like manner to tuples, arrays and slices can be destructured this way: |
| 4 | + |
| 5 | +```rust,editable |
| 6 | +fn main() { |
| 7 | + // Try changing the values in the array, or make it a slice! |
| 8 | + let array = [1, -2, 6]; |
| 9 | +
|
| 10 | + match array { |
| 11 | + // Binds the second and the third elements to the respective variables |
| 12 | + [0, second, third] => |
| 13 | + println!("array[0] = 0, array[1] = {}, array[2] = {}", second, third), |
| 14 | +
|
| 15 | + // Single values can be ignored with _ |
| 16 | + [1, _, third] => println!( |
| 17 | + "array[0] = 1, array[2] = {} and array[1] was ignored", |
| 18 | + third |
| 19 | + ), |
| 20 | +
|
| 21 | + // You can also bind some and ignore the rest |
| 22 | + [-1, second, ..] => println!( |
| 23 | + "array[0] = -1, array[1] = {} and all the other ones were ignored", |
| 24 | + second |
| 25 | + ), |
| 26 | + // The code below would not compile |
| 27 | + // [-1, second] => ... |
| 28 | +
|
| 29 | + // Or store them in another array/slice (the type depends on |
| 30 | + // that of the value that is being matched against) |
| 31 | + [3, second, tail @ ..] => println!( |
| 32 | + "array[0] = 3, array[1] = {} and the other elements were {:?}", |
| 33 | + second, tail |
| 34 | + ), |
| 35 | +
|
| 36 | + // Combining these patterns, we can, for example, bind the first and |
| 37 | + // last values, and store the rest of them in a single array |
| 38 | + [first, middle @ .., last] => println!( |
| 39 | + "array[0] = {}, middle = {:?}, array[2] = {}", |
| 40 | + first, middle, last |
| 41 | + ), |
| 42 | + } |
| 43 | +} |
| 44 | +``` |
| 45 | + |
| 46 | +### See also: |
| 47 | + |
| 48 | +[Arrays and Slices](../../../primitives/array.md) |
0 commit comments