Add additional constraints on generic types for more control.
fn sum_all<T>(list: &[T]) -> Option<T>
where T: std::ops::Add<Output = T> + Copy // Use Add trait and Copy trait
{
if list.is_empty() {
return None;
}
let mut sum = list[0];
for &item in &list[1..] { // Iterate from the second element onwards
sum = sum + item;
}
Some(sum)
}
fn main() {
let numbers: Vec<i32> = vec![1, 2, 3];
let sum = sum_all(&numbers);
match sum {
Some(value) => println!("Sum: {}", value),
None => println!("Empty list"),
}
}