Multiple bounds
- Rust course
- Intermediate
- Lesson 20/115
- 4 min
Combine multiple trait bounds with +.
Multiple bounds
If a type parameter needs several behaviours, the bounds are combined with +:
use std::fmt::Display;
fn buyuk_olan<T: PartialOrd + Display>(a: T, b: T) -> String {
if a > b {
format!("{a}")
} else {
format!("{b}")
}
}PartialOrd is needed for comparing, Display for formatting. The order doesn't matter.
PartialOrd vs Ord
PartialOrd allows some values to be incomparable: f64::NAN < 1.0 and f64::NAN > 1.0 are both false. Ord requires a total order; integers and strings are Ord, floats are not.
let mut v = vec![3, 1, 2];
v.sort(); // needs Ord: i32 is fine
let mut f = vec![2.5, 1.0];
// f.sort(); // error: f64 isn't Ord
f.sort_by(|a, b| a.total_cmp(b));Practice Print the larger
Write the buyuk_olan function above. Print the results for (3, 8) and ("elma", "armut") separated by a space.
Starter code
use std::fmt::Display;
fn main() {
// buraya yaz
}Sample solution
use std::fmt::Display;
fn buyuk_olan<T: PartialOrd + Display>(a: T, b: T) -> String {
if a > b {
format!("{a}")
} else {
format!("{b}")
}
}
fn main() {
println!("{} {}", buyuk_olan(3, 8), buyuk_olan("elma", "armut"));
}Expected output
8 elma
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>buyuk_olan("elma", "armut")</code> return?
- "elma" Correct answer
- "armut"
- Compile error
- "elmaarmut"
Explanation: Texts compare in lexicographic order; since "e" > "a", elma is greater.
2 Combine bounds
fn buyuk_olan<T: PartialOrd ____ Display>(a: T, b: T) -> String
fn buyuk_olan<T: PartialOrd + Display>(a: T, b: T) -> String
Explanation: Several trait bounds are combined with +.
3 Type and what it implements
| Term | Meaning |
|---|---|
i32 |
Ord + Copy |
f64 |
PartialOrd (not Ord) |
&str |
Ord + Display |
Vec<i32> |
Ord, not Display |