capypad
0 day streak
rust / intermediate
Snippet

Trait Bounds and where Clauses

Trait bounds constrain generic types to only accept types implementing certain behaviors. The `where` clause provides cleaner syntax for complex bounds compared to inline notation. Combining multiple trait bounds allows you to use multiple behaviors on generic types.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use std::fmt::{Display, Debug};
 
#[derive(Debug)]
struct Point {
x: f64,
y: f64,
}
 
impl Display for Point {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
 
fn print_both<T>(item: T)
where
T: Display + Debug,
{
println!("Display: {}", item);
println!("Debug: {:?}", item);
}
 
fn max<T>(a: T, b: T) -> T
where
T: PartialOrd + Copy,
{
if a >= b { a } else { b }
}
 
fn main() {
let p = Point { x: 1.0, y: 2.0 };
print_both(p);
println!("Max: {}", max(5, 10));
}
Breakdown
1
where T: Display + Debug,
Where clause combining multiple trait requirements cleanly
2
T: PartialOrd + Copy
Multiple bounds requiring both comparison and copy semantics
3
if a >= b { a } else { b }
Generic comparison logic works on any PartialOrd type