liveBook · Manning

Trait bound

As explained in Learn Rust in a Month of Lunches

A trait bound is a Rust constraint requiring a type to implement one or more specified traits before it can be used in a bounded context.

A trait bound requires a type to implement a particular trait before it can be used. Think of it as a qualification: a function need not care what the type is, as long as it meets the requirements. section 7.1.3 section 7.1.4

Write a bound after a colon, as in `T: PartialOrd + Display`. The `+` means that `T` must implement both traits. The bounds let a function compare values and print them, while still accepting more than one type. section 12.2.1

use std::fmt::Display;
 
fn print_maximum<T: PartialOrd + Display>(one: T, two: T) {
    let higher = if one > two { one } else { two };
    println!("{higher} is higher.");
}
 
fn main() {
    print_maximum(8, 10);
}

Here `one` and `two` share the same type `T`. The bounds allow `print_maximum` to compare and display them. section 12.2.1

You can also put bounds in a `where` clause. A trait can be a requirement even if it has no methods: implementing it can still qualify a type for a function. section 7.1.3

use std::fmt::Debug;
 
struct Monster {
    health: i32,
}
 
#[derive(Debug)]
struct Wizard {
    health: i32,
}
#[derive(Debug)]
struct Ranger {
    health: i32,
}
 
trait Magic {}                            #1
trait FightClose {}                       #2
trait FightFromDistance {}
 
impl FightClose for Ranger {}
impl FightClose for Wizard {}
impl FightFromDistance for Ranger {}      #3
impl Magic for Wizard {}                  #4
 
fn attack_with_bow<T>(pc: &T, opponent: &mut Monster, distance: u32)
where
    T: FightFromDistance + Debug,
{
    if distance < 10 {
        opponent.health -= 10;
        println!(
            "Bow attack! Opponent's health: {}.  You are now at: {pc:?}",
            opponent.health
        );
    }
}
 
fn attack_with_sword<T>(pc: &T, opponent: &mut Monster)
where
    T: FightClose + Debug,
{
    opponent.health -= 10;
    println!(
        "Sword attack! Opponent's health: {}. You are now at: {pc:?}",
        opponent.health
    );
}
 
fn fireball<T>(pc: &T, opponent: &mut Monster, distance: u32)
where
    T: Magic + Debug,
{
    if distance < 15 {
        opponent.health -= 20;
        println!(
            "A massive fireball! Opponent's health: {}. You are now at:
            {pc:?}",
            opponent.health
        );
    }
}
 
fn main() {
    let radagast = Wizard { health: 60 };
    let aragorn = Ranger { health: 80 };
 
    let mut uruk_hai = Monster { health: 40 };
 
    attack_with_sword(&radagast, &mut uruk_hai);
    attack_with_bow(&aragorn, &mut uruk_hai, 8);
    fireball(&radagast, &mut uruk_hai, 8);
}
#1 No methods for any of these traits! They are just trait bounds.
#2 Each type gets FightClose.
#3 But only Ranger gets FightFromDistance.
#4 And only Wizard gets Magic.

The attack functions use `where` clauses to require a game skill trait and `Debug`. The skill traits have no methods. section 7.1.3

A trait definition can require another trait too. In `trait MonsterBehavior: Debug`, every type implementing `MonsterBehavior` must also implement `Debug`. That lets a default method print `self` with `{:?}`. section 7.1.2

Argument-position `impl Trait` is a shorter way to accept a type with a trait. But two separate `impl PartialOrd + Display` parameters do not promise the same type. If the function needs the arguments to share a type, name it with a generic parameter such as `T`. section 12.2.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains inline and where-clause bounds, multiple requirements, and same-type limitations of separate impl Trait parameters.
Examples
Uses game attack functions, a generic maximum function, and closure signatures to illustrate bounds.
What you can do after
Apply trait bounds in Rust to require capabilities and keep related function arguments the same type.
How it connects
Connects trait bounds to generics, default trait methods, closures, and iterator methods.

Also explained in

Compare how 2 books explain trait bound →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.