Skip to content

Require a Behavior with a Trait Bound

The Course
•
28 min study

The last lesson ended with a generic method that could not print its payload, because nothing said that every T can be printed. The queue has the same problem with its own types. A report should work for books and for chapters, which store their names differently, but a generic function cannot call .label() on a T it knows nothing about. It needs a promise.

A trait is that promise: a named list of methods a type can provide. trait Label { fn label(&self) -> &str; } declares the method without a body. impl Label for Book supplies the body for one type. Then a bound such as T: Label on a generic function means "any T, as long as it implements Label". Inside the function, the compiler allows exactly the methods the bound guarantees, and at every call it checks that the concrete type keeps the promise.

Predict and run

Why does one show call accept a Book and the other a Chapter?

Predict, then run Rust
trait Label {
    fn label(&self) -> &str;
}

struct Book(String);
struct Chapter(String);

impl Label for Book {
    fn label(&self) -> &str { &self.0 }
}

impl Label for Chapter {
    fn label(&self) -> &str { &self.0 }
}

fn show<T: Label>(item: &T) {
    println!("Reading: {}", item.label());
}

fn main() {
    show(&Book(String::from("Rust")));
    show(&Chapter(String::from("Traits")));
}
Check your prediction
Text
Reading: Rust
Reading: Traits

Both types implement Label, so both satisfy T: Label. The compiler builds one version of show for Book and one for Chapter, each calling the right label. The argument is a shared borrow, so show reads the record without taking ownership. Now add show(&42); at the start of main. Predict where the error points: at show, or at the call?

An unsatisfied bound

The call is rejected:

Rust
fn main() {
    show(&42);
}

The error is error[E0277]: the trait bound {integer}: Label is not satisfied, with the note "required by a bound in show". It points at the call, because that is where the promise is broken; the body of show is fine for every type that meets the bound. A help line then lists the types that do satisfy it: "the following other types implement trait Label", pointing at the impl Label for Book and impl Label for Chapter blocks. The bound is met type by type, and only those two types have met it. The fix is either to pass a type that implements Label, or to write impl Label for that type, if a label makes sense for it.

Without the bound, the error moves into the function instead: fn show<T>(item: &T) that calls item.label() fails with error[E0599]: no method named label found for reference &T. A bound is what makes the method available.

Default methods and bounded impls

A trait can also provide a method with a body. Every implementing type gets it for free and only writes the required methods. Bounds also work on impl blocks, which finally fixes the method the last lesson could not write.

Share a default method and bound an impl Rust
trait Label {
    fn label(&self) -> &str;

    fn heading(&self) -> String {
        format!("== {} ==", self.label())
    }
}

struct Book(String);
struct Chapter { book: String, number: u32 }

impl Label for Book {
    fn label(&self) -> &str { &self.0 }
}

impl Label for Chapter {
    fn label(&self) -> &str { &self.book }

    fn heading(&self) -> String {
        format!("== {}, chapter {} ==", self.book, self.number)
    }
}

struct Tagged<T> {
    id: u32,
    value: T,
}

impl<T: Label> Tagged<T> {
    fn describe(&self) {
        println!("#{} {}", self.id, self.value.heading());
    }
}

fn main() {
    let book = Tagged { id: 7, value: Book(String::from("Rust Patterns")) };
    let chapter = Tagged { id: 8, value: Chapter { book: String::from("Rust Patterns"), number: 3 } };
    book.describe();
    chapter.describe();
}
Text
#7 == Rust Patterns ==
#8 == Rust Patterns, chapter 3 ==

Book uses the default heading, built from its label. Chapter overrides it with its own version. impl<T: Label> Tagged<T> adds describe only to tags whose payload has a label, so Tagged<u32> simply has no describe, while Tagged<T> itself still accepts any payload. Long bounds can be moved after the signature with where: fn show<T>(item: &T) where T: Label means the same as the version above.

No runtime cost

A generic function with a bound is checked once and compiled into a separate copy for each concrete type. Each call goes straight to the right method, as if you had written the function for that type by hand.

Practice

Exercise

Your turn

Define a trait PageEstimate with fn pages(&self) -> u32, and implement it for Book(u32) and for Bundle(u32, u32), where a bundle's estimate is the sum of its two parts. A generic show prints the estimate. Calling it with Book(120) and Bundle(25, 50) should print 120 pages and 75 pages.

Your working space Rust
struct Book(u32);
struct Bundle(u32, u32);

fn main() {
    // Pass Book(120) and Bundle(25, 50) to show.
}
Hint 1: the idea

The trait exposes a page estimate without revealing how it is calculated. Each type writes its own rule, and show only relies on the trait.

Hint 2: a first step

Declare trait PageEstimate { fn pages(&self) -> u32; }, then write fn show<T: PageEstimate>(item: &T).

Worked solution
Run the solution Rust
trait PageEstimate {
    fn pages(&self) -> u32;
}

struct Book(u32);
struct Bundle(u32, u32);

impl PageEstimate for Book {
    fn pages(&self) -> u32 { self.0 }
}

impl PageEstimate for Bundle {
    fn pages(&self) -> u32 { self.0 + self.1 }
}

fn show<T: PageEstimate>(item: &T) {
    println!("{} pages", item.pages());
}

fn main() {
    show(&Book(120));
    show(&Bundle(25, 50));
}
Text
120 pages
75 pages

The bound makes pages available for either type, and each implementation supplies its own rule. Adding a third type, such as a Series of three volumes, needs only a new impl; show stays unchanged. The next lesson uses traits that the standard library already defines, such as Display.

Was this article helpful?

Your response is saved on this device.