capypad
0 day streak
rust / intermediate
Snippet

Multiple Trait Bounds with the + Operator

Trait bounds can be combined using + to require a type implement multiple traits. This allows functions to use functionality from several traits simultaneously, providing flexibility in generic constraints.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::fmt::{Debug, Display};
 
fn print_debug<T>(item: &T)
where
T: Debug + Display,
{
println!("Debug: {:?}, Display: {}", item, item);
}
 
fn main() {
let num = 42;
print_debug(&num);
}
Breakdown
1
T: Debug + Display,
Type T must implement both Debug AND Display traits
2
println!("Debug: {:?}, Display: {}", item, item);
Can call both Debug formatting and Display formatting on item