RRust By Example
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

Trait bounds constrain generic types. Use where for complex bounds.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the generics category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Generics Examples