0PricingLogin
Learn Rust Coding · Lesson

Trait Bounds

Constrain generics with traits.

What Trait Bounds Do

A trait bound restricts a generic type to those that implement a given trait. It tells the compiler what behavior the type guarantees.

This unlocks the trait's methods inside the generic code while keeping the function usable for many types.

Inline Bound Syntax

The simplest form places the bound right after the type parameter: T: Trait. Here T must implement Display so it can be printed.

Inside the function you may now call any method that Display provides.

use std::fmt::Display;

fn show<T: Display>(value: T) {
    println!("value = {}", value);
}

All lessons in this course

  1. Generic Functions
  2. Generic Structs and Enums
  3. Trait Bounds
  4. where Clauses and Multiple Bounds
← Back to Learn Rust Coding