Constrained Generics with where
Write a generic Rust function with a where clause that sums all elements of a slice. The function must be generic over any type T that implements the Sum trait (for summing via .iter().copied().sum()) and the Copy trait (for copying elements from the iterator).
Where clauses in Rust allow specifying trait bounds on generic types in a separate clause after the function signature, rather than inline before the parameters. This makes complex bounds more readable: fn sum
Where clauses are especially important for complex generic functions with multiple type parameters and associated type constraints. They enable expressing relationships between types that would be impossible with simple inline bounds. The Sum trait in particular requires careful handling because it involves the iterator pattern.
Time complexity is O(n) where n is the slice length. Space complexity is O(1). The generic function is monomorphized at compile time, creating a specialized version for each concrete type used, with zero runtime overhead from the abstraction.
Edge cases include empty slices (sum of zero elements returns the identity value via Sum::sum()), single-element slices, negative values, and ensuring the Copy trait bound allows the iterator to copy elements rather than consume them.
Example Input & Output
10+20+30 = 60
-5+5+10 = 10
Single element
Empty slice returns 0
Sum of i32 slice: 1+2+3+4+5 = 15
Algorithm Flow

Solution Approach
Best Answers
use std::iter::Sum;
fn solution<T: Sum + Copy>(items: &[T]) -> T {
items.iter().copied().sum()
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
