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.

RustData Integrity

Code

rustsnippet
21 lines
#[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

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:`.