rust / intermediate
Snippet
Slice Patterns in Function Parameters
Slice patterns in match expressions destructure arrays and slices concisely. The .. matches the rest of the slice, allowing you to capture specific elements while ignoring the remainder. Combined with function parameters, this enables flexible slice handling.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
fn sum_first_three(arr: &[i32]) -> Option<i32> {match arr {[a, b, c, ..] => Some(a + b + c),_ => None,}}fn main() {let nums = [1, 2, 3, 4, 5];println!("{:?}", sum_first_three(&nums));}
Breakdown
1
[a, b, c, ..]
Binds first three elements, ignores remaining with ..
2
arr: &[i32]
Function accepts a slice reference, not an owned array