Cmp Min And Max With Ord Bounds

std::cmp::min and max pick bounds for any Ord type, and nesting them clamps a value into a range without a hand-written if.

RustData Integrity

Code

rustsnippet
20 lines
use std::cmp::{max, min};

// std::cmp::min and max give Ord types their bounds
fn clamp<T: Ord>(value: T, low: T, high: T) -> T {
    min(max(value, low), high)
}

fn main() {
    let readings = [-3i32, 7, 42];

    for &value in &readings {
        let bounded = clamp(value, 0, 100);
        println!("{value} -> {bounded}");
    }

    // min/max also compare strings and any other Ord type
    let names = ["ada", "grace", "linus"];
    println!("first: {}", min(names[0], names[1]));
    println!("last: {}", max("zeta", "alpha"));
}

How the snippet works

Cmp Min And Max With Ord Bounds is built around the functions clamp and main.

Repetition is confined to for &value in &readings — the rest of the file is straight-line.

Applying it

The run prints first:, last: — each prefix names the step that produced it.

Running the file executes main, which drives clamp in order.

Statements that matter

fn clamp<T: Ord>(value: T, low: T, high: T) -> T {
    min(max(value, low), high)
}

Interactive Tools for This Topic

FAQ

What does Cmp Min And Max With Ord Bounds print when run?
Run it as a complete program — the output lines carry labels such as `first:`, `last:`.