std-method

slice::sort_by_key

Sort by a derived key rather than by the whole element. This stable sort preserves original order for records with equal keys. Expected stdout (not executed): [(1, "B"), (2, "A"), (2, "C")] Common mistake: Assuming the key function is called exactly once per item.

Formal Syntax & Structure

rust syntaxrust
slice.sort_by_key(|item| key)

Working Example

Example Snippetrust
fn main() {    let mut jobs = [(2, "A"), (1, "B"), (2, "C")];    jobs.sort_by_key(|job| job.0);    println!("{jobs:?}");}
Rust Reference