patternrustTip
Generic bounds with where clauses for readable constraints
Viewed 0 times
genericsboundswhere clausetrait constraintsmonomorphizationassociated types
Error Messages
Problem
Functions with multiple generic parameters and trait bounds become unreadable when all constraints are crammed into angle brackets.
Solution
Use where clauses to separate generic parameters from their constraints:
use std::fmt::{Debug, Display};
// Hard to read inline style
fn print_pair_inline<T: Debug + Display, U: Debug + Clone>(a: T, b: U) {
println!("{} {:?} {:?}", a, b.clone(), b);
}
// Much cleaner with where clause
fn print_pair<T, U>(a: T, b: U)
where
T: Debug + Display,
U: Debug + Clone,
{
println!("{} {:?} {:?}", a, b.clone(), b);
}
// Common bounds in structs
struct Wrapper<T>
where
T: Clone + Debug,
{
value: T,
}
impl<T> Wrapper<T>
where
T: Clone + Debug,
{
pub fn get(&self) -> T {
self.value.clone()
}
}Why
where clauses align constraints vertically, making them easier to scan. They also allow expressing constraints that cannot be written in angle brackets, such as associated type bounds.
Gotchas
- T: 'static as a bound means T contains no non-static references — it does not mean T lives forever
- You can bound associated types: where T: Iterator<Item = u32>
- Trait bounds in impl blocks must repeat the same bounds as in the struct definition
Revisions (0)
No revisions yet.