liveBook · Manning

PartialOrd

As explained in Learn Rust in a Month of Lunches

PartialOrd is the Rust trait that provides partial ordering and comparison operations for values.

PartialOrd is a Rust trait that lets a generic type use comparison operators such as <, >, and ==. A type parameter needs this trait when a function compares its values. section 5.1

Combine PartialOrd with other trait bounds when the same values must also be displayed. The bound U: Display + PartialOrd requires U to support both formatted output and comparisons. section 5.1

use std::fmt::Display;
use std::cmp::PartialOrd;
 
fn compare_and_display<T: Display, U: Display + PartialOrd>(statement: T,
input_1: U, input_2: U) {
    println!("{statement}! Is {input_1} greater than {input_2}? {}",
    input_1 > input_2);
}
 
fn main() {
    compare_and_display("Listen up!", 9, 8);
}

This example compares two generic U values with > while displaying them, using PartialOrd alongside Display. section 5.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines the trait bound and demonstrates it in a generic function, without developing the trait's implementation details.
Examples
Uses compare_and_display with the values 9 and 8 to print whether 9 is greater than 8.
What it assumes
Assumes basic generics and trait bounds, while illustrating how multiple bounds combine with the + syntax.
What you can do after
Apply it in generic functions that compare values while optionally combining it with Display for output.
How it connects
Connects PartialOrd with generics, traits, Display, trait bounds, and comparison operators.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.