Trait Bounds
In this page:
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
use std::fmt::Display;
fn print_it<T: Display>(item: T) {
println!("Item: {}", item);
}
fn main() {
print_it(42);
print_it("text");
}
Login to try C/C++/Java/PHP code in the editor
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
use std::fmt::Debug;
fn show<T: Debug + Clone>(item: T) {
let copy = item.clone();
println!("{:?}", copy);
}
fn main() {
show(vec![1, 2, 3]);
}
Login to try C/C++/Java/PHP code in the editor
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
use std::fmt::Display;
fn announce(item: impl Display) {
println!("Announcing: {}", item);
}
fn main() {
announce("New release");
}
Login to try C/C++/Java/PHP code in the editor
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
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"));
}
Login to try C/C++/Java/PHP code in the editor
- Trying to call a trait's method inside a generic function without first constraining the type parameter with that trait.
- Writing overly restrictive trait bounds that exclude types which would otherwise work fine.
- Confusing
impl Traitparameter syntax with generic<T: Trait>syntax -- they're closely related but not always interchangeable.
- 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 Traitin a parameter position is shorthand syntax for a simple, single-use trait bound.whereclauses 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: