Card 1 / 14
Sum all elements of a slice. Slices &[T] are borrowed views of contiguous data; .iter() yields references to the elements, and .sum() consumes the iterator and adds them up.
arr |
result | notes |
|---|---|---|
[1, 2, 3, 4, 5] |
15 |
happy path |
[] |
0 |
empty slice sums to zero |
[-1, 1, -2, 2] |
0 |
negatives cancel |
arr.iter().sum() β that's all you need!
/// Sum all elements in the array
fn sum(arr: &[i32]) -> i32 {
arr.iter().sum()
}Card 2 / 14
Return the largest element of a slice. .max() returns Option<T> because the iterator might be empty (.min() is its mirror image), and .copied() turns an Iterator<Item = &T> into an Iterator<Item = T> for Copy types.