capypad
0 day streak
rust / intermediate
Snippet

Generic Traits with Where Clauses

Where clauses provide a cleaner way to express complex generic constraints compared to inline trait bounds. They allow multiple constraints on a single type parameter and become essential when dealing with several generic parameters or complex trait combinations.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::fmt::{Display, Debug};
 
fn print_debug<T, U>(t: T, u: U) -> String
where
T: Display + Debug,
U: Clone + Into<String>,
{
format!("T: {:?}, U: {}", t, u.clone())
}
 
fn main() {
println!("{}", print_debug(42, "hello"));
}
Breakdown
1
use std::fmt::{Display, Debug};
Import Display and Debug traits needed for the generic constraints
2
fn print_debug<T, U>(t: T, u: U) -> String
Function with two generic type parameters T and U
3
where T: Display + Debug,
T must implement both Display (for printing) and Debug (for {:?} formatting)
4
U: Clone + Into<String>,
U must be cloneable and convertible into a String
5
format!("T: {:?}, U: {}", t, u.clone())
Uses Debug formatting for t and clones u to satisfy the Into<String> constraint