Code Logo

Constrained Generics with where

Published at25 Jul 2026
Rust Functions Hard 0 views
Like0

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(items: &[T]) -> T where T: Sum + Copy { ... }. Multiple bounds can be combined with +.

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

Example 1
Input
[10,20,30]
Output
60
Explanation

10+20+30 = 60

Example 2
Input
[-5,5,10]
Output
10
Explanation

-5+5+10 = 10

Example 3
Input
[1]
Output
1
Explanation

Single element

Example 4
Input
[]
Output
0
Explanation

Empty slice returns 0

Example 5
Input
[1,2,3,4,5]
Output
15
Explanation

Sum of i32 slice: 1+2+3+4+5 = 15

Algorithm Flow

Recommendation Algorithm Flow for Constrained Generics with where
Recommendation Algorithm Flow for Constrained Generics with where

Solution Approach

use std::iter::Sum;

fn solution<T: Sum + Copy>(items: &[T]) -> T {
    items.iter().copied().sum()
}

Best Answers

rust - Approach 1
use std::iter::Sum;

fn solution<T: Sum + Copy>(items: &[T]) -> T {
    items.iter().copied().sum()
}