Bounds and where clauses
Quick answer
Trait bounds let generic code require specific operations. Express those requirements in the signature so callers know which types are accepted.
Specify only required behavior
T: Display requires formatting with {}. Combine requirements with + and move longer constraints into a where clause. Avoid requiring Clone, Copy or other behavior that the function never uses.
use std::fmt::Display;fn label<T: Display>(value: T) -> String { format!("value={value}") }fn main() { println!("{}", label(12)); }Expected stdout (not executed):
value=12Display supplies the required formatting operation.
use std::fmt::Display;fn same<T>(a: T, b: T) where T: Display + PartialEq { println!("{a} equals {b}: {}", a == b);}fn main() { same(4, 5); }Expected stdout (not executed):
4 equals 5: falsePartialEq permits comparison and Display permits formatting.
Common mistake
A generic parameter does not automatically implement every trait.
Try it yourself
Write a generic function that compares two values for equality without requiring Display.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bounds and where clauses — practice quiz
Choose one answer per question, then review the explanation.
What is equivalent to `fn show<T: Display>(x: T)`?
What does `T: Display + Clone` require?
A function reads a value using Display but never clones it. Why remove an unnecessary Clone bound?