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.
Code
#[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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Sort By Tuple Keys For Multi Field Order?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.