← Back to Rust Course | Chapter 11: Generics & Traits | Lesson 4 of 7

Trait Bounds

A trait bound tells a generic function "only give me types that can already do this specific thing."

Adding a Simple Trait Bound

A trait bound after a colon in the generic parameter list restricts the generic type to only those implementing that specific trait, unlocking use of its methods inside the function.

Example: Adding a Simple Trait Bound

markup
use std::fmt::Display;

fn print_it<T: Display>(item: T) {
    println!("Item: {}", item);
}

fn main() {
    print_it(42);
    print_it("text");
}

Combining Multiple Trait Bounds

Several trait bounds can be combined with +, requiring the generic type to implement all of them at once.

Example: Combining Multiple Trait Bounds

markup
use std::fmt::Debug;

fn show<T: Debug + Clone>(item: T) {
    let copy = item.clone();
    println!("{:?}", copy);
}

fn main() {
    show(vec![1, 2, 3]);
}

impl Trait Parameter Shorthand

impl TraitName used directly as a parameter type is shorthand for a simple generic bound, useful when you don't need to name the type parameter explicitly.

Example: impl Trait Parameter Shorthand

markup
use std::fmt::Display;

fn announce(item: impl Display) {
    println!("Announcing: {}", item);
}

fn main() {
    announce("New release");
}

Using a where Clause

For functions with several generic parameters and bounds, a where clause after the signature keeps the function declaration itself more readable.

Example: Using a where Clause

markup
use std::fmt::Display;

fn combine<T, U>(a: T, b: U) -> String
where
    T: Display,
    U: Display,
{
    format!("{} and {}", a, b)
}

fn main() {
    println!("{}", combine(1, "two"));
}
Common Mistakes
  1. Trying to call a trait's method inside a generic function without first constraining the type parameter with that trait.
  2. Writing overly restrictive trait bounds that exclude types which would otherwise work fine.
  3. Confusing impl Trait parameter syntax with generic <T: Trait> syntax -- they're closely related but not always interchangeable.
Chapter Summary
  • A trait bound, written T: TraitName, restricts a generic type parameter to types implementing that trait.
  • Multiple bounds can be combined with +, e.g. T: Debug + Clone.
  • impl Trait in a parameter position is shorthand syntax for a simple, single-use trait bound.
  • where clauses offer an alternative, more readable syntax for expressing bounds, especially with multiple parameters.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.