rust / intermediate
Snippet
Slice Pattern Matching
Slices können in Patterns dekonstruiert werden. [a, b, ..] erfasst die ersten zwei Elemente. Der .. matches alle restlichen Elemente. [head, tail @ ..] bindet head separat während tail an den Rest des Slices gebunden wird.
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));}
Erklärung
1
[a, b, ..] => Some(a + b)
Pattern matcht Slice mit mindestens 2 Elementen, bindet sie an a und b
2
[a] => Some(*a)
Matcht Slice mit genau einem Element
3
[head, tail @ ..]
head bekommt erstes Element, tail@ bindet Rest des Slices an tail