rust / intermediate
Snippet
Trait Bounds and Generic Constraints
Trait bounds constrain generic types to only accept values that implement certain behaviors. You can combine multiple bounds with +. The impl Trait syntax provides a shorter way to specify constraints in function signatures. Return types can also use impl Trait to indicate they return something implementing a trait without specifying the concrete type.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::fmt::{Display, Debug};fn print_debug<T: Debug>(value: T) {println!("{:?}", value);}fn compare_and_display<T: Display + PartialOrd>(a: T, b: T) {println!("{} vs {}", a, b);}fn dynamic_display(item: impl Display + Debug) {println!("Debug: {:?}, Display: {}", item, item);}fn returns_comparable() -> impl PartialOrd {42}
Breakdown
1
fn print_debug<T: Debug>(value: T)
Generic function where T must implement the Debug trait to allow debug formatting
2
fn compare_and_display<T: Display + PartialOrd>
T must implement both Display and PartialOrd traits, enabling both printing and comparison
3
fn dynamic_display(item: impl Display + Debug)
impl Trait syntax as alternative to generic syntax for the same constraint
4
fn returns_comparable() -> impl PartialOrd
Return type hides concrete type but promises it implements PartialOrd