intermediateGenerics
Trait Bounds
Constrain generic types with trait bounds.
Trait Bounds
Constrain generic types with trait bounds.
Difficulty
Intermediate
Code
rust
use std::fmt::Display;
fn print_pair<T: Display, U: Display>(first: T, second: U) {
println!("{}, {}", first, second);
}
fn sum<T>(items: &[T]) -> T
where
T: std::ops::Add<Output = T> + Copy + Default,
{
let mut total = T::default();
for &item in items {
total = total + item;
}
total
}
fn main() {
print_pair(42, "hello");
println!("sum: {}", sum(&[1, 2, 3, 4, 5]));
}Explanation
This example demonstrates how to use trait bounds in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the generics category to build a complete understanding of this topic.