CodeBlanks Logo Icon CodeBlanks

Multiple bounds

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

main.rs
use std::fmt::Display;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
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

Question
fn buyuk_olan<T: PartialOrd ____ Display>(a: T, b: T) -> String
Answer
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

All lessons in Intermediate