max_by And min_by Pick Extremes By Comparator

Pick extremes with max_by and min_by using a comparator instead of a key, including the documented tie rules: last maximum, first minimum.

RustData Integrity

Code

rustsnippet
26 lines
#[derive(Debug, Clone, Copy)]
struct Task {
    name: &'static str,
    priority: u8,
}

fn main() {
    let tasks = [
        Task { name: "index", priority: 3 },
        Task { name: "auth", priority: 9 },
        Task { name: "cache", priority: 9 },
        Task { name: "report", priority: 1 },
    ];

    // max_by 用比较器挑最大:并列最大时返回最后一个
    let top = tasks.iter().max_by(|a, b| a.priority.cmp(&b.priority));
    println!("max_by -> {:?}", top);

    // min_by 同理:并列最小时返回第一个
    let bottom = tasks.iter().min_by(|a, b| a.priority.cmp(&b.priority));
    println!("min_by -> {:?}", bottom);

    // 反转比较器即从另一端取值:max_by 也能拿最小
    let reversed = tasks.iter().max_by(|a, b| b.priority.cmp(&a.priority));
    println!("max_by reversed -> {:?}", reversed);
}

What the code does

max_by And min_by Pick Extremes By Comparator reduces to the function main.

Applying it

Running the file prints labeled results such as max_by ->, min_by ->, max_by reversed -> — each operation’s effect is visible in the output.

Statements that matter

let reversed = tasks.iter().max_by(|a, b| b.priority.cmp(&a.priority));
let bottom = tasks.iter().min_by(|a, b| a.priority.cmp(&b.priority));
let top = tasks.iter().max_by(|a, b| a.priority.cmp(&b.priority));

Interactive Tools for This Topic

FAQ

What does max_by And min_by Pick Extremes By Comparator print when run?
The script runs standalone; its 3 labeled outputs include `max_by ->`, `min_by ->`, `max_by reversed ->`.