Sort By Tuple Keys For Multi Field Order

Order tickets by several fields at once with a tuple sort key, pairing the ascending priority with Reverse around the descending age value.

RustData Integrity

Code

rustsnippet
22 lines
#[derive(Debug)]
struct Ticket {
    priority: u8,
    age_days: u32,
    title: &'static str,
}

fn main() {
    let mut queue = vec![
        Ticket { priority: 2, age_days: 9, title: "billing export" },
        Ticket { priority: 1, age_days: 30, title: "login outage" },
        Ticket { priority: 2, age_days: 2, title: "typos in docs" },
        Ticket { priority: 1, age_days: 12, title: "slow queries" },
    ];

    // 多字段(field)排序用元组(tuple)键:priority 升序在前,
    // Reverse 包住 age_days 做降序在后,稳定性由 sort_by_key 保证
    queue.sort_by_key(|t| (t.priority, std::cmp::Reverse(t.age_days)));
    for t in &queue {
        println!("p{} d{} {}", t.priority, t.age_days, t.title);
    }
}

What the code does

Sort By Tuple Keys For Multi Field Order reduces to the function main.

for t in &queue is the loop that carries the per-item work.

Iteration is driven by for t in &queue.

Statements that matter

queue.sort_by_key(|t| (t.priority, std::cmp::Reverse(t.age_days)));

Interactive Tools for This Topic

FAQ

How do you run Sort By Tuple Keys For Multi Field Order?
Direct execution is enough; the script has no external requirements.