rust / intermediate
Snippet
Slice Pattern Matching
Slices can be destructured in patterns. [a, b, ..] captures the first two elements. The .. matches any remaining elements. [head, tail @ ..] binds head separately while binding tail to the rest of the slice.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fn sum_first_two(numbers: &[i32]) -> Option<i32> {match numbers {[a, b, ..] => Some(a + b),[a] => Some(*a),[] => None,}}fn match_head_tail(slice: &[u8]) -> (&[u8], &[u8]) {match slice {[head, tail @ ..] => (tail, tail),[] => (&[], &[]),}}fn main() {let arr = [1, 2, 3, 4, 5];println!("Sum of first two: {:?}", sum_first_two(&arr));println!("Head-tail: {:?}", match_head_tail(&arr));let empty: &[i32] = &[];println!("Empty: {:?}", sum_first_two(empty));}
Breakdown
1
[a, b, ..] => Some(a + b)
Pattern matches slice with at least 2 elements, binds them to a and b
2
[a] => Some(*a)
Matches slice with exactly one element
3
[head, tail @ ..]
head gets first element, tail@ binds rest of slice to tail