Sort By Cached Key Decorate
Sort with slice::sort_by_cached_key so each key is computed once per element instead of on every pairwise comparison.
Code
#[derive(Debug)]
struct Record {
name: &'static str,
title: &'static str,
}
fn main() {
let mut records = vec![
Record { name: "Zoe", title: "engineer" },
Record { name: "adam", title: "Analyst" },
Record { name: "Mia", title: "designer" },
];
// sort_by_cached_key decorates once, then sorts on the cached keys
records.sort_by_cached_key(|record| record.name.to_lowercase());
println!("by name: {:?}", records.iter().map(|r| r.name).collect::<Vec<_>>());
records.sort_by_cached_key(|record| (record.title.len(), record.title.to_lowercase()));
println!("by title: {:?}", records.iter().map(|r| r.title).collect::<Vec<_>>());
println!("names untouched: {:?}", records.iter().map(|r| r.name).collect::<Vec<_>>());
}Inside the snippet
Structurally, expect the function main and nothing else.
Caveats
- Entirely standard-library — copy it in and it runs.
Putting it to use
The primary signature is fn main()
Look for the by name:, by title:, names untouched: prefixes when the file runs; they tie each line to its step.
Core lines
records.sort_by_cached_key(|record| (record.title.len(), record.title.to_lowercase()));
records.sort_by_cached_key(|record| record.name.to_lowercase());
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
- What does Sort By Cached Key Decorate print when run?
- The script runs standalone; its 3 labeled outputs include `by name:`, `by title:`, `names untouched:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.