Skip to content
Justice Tech School

Sorting

sort works on Vec. sort_by and sort_by_key take custom rules.

Example
fn main() {
    let mut v = vec![3, 1, 2];
    v.sort();
    let mut w = vec!["pear", "fig", "apple"];
    w.sort_by_key(|s| s.len());
    println!("{:?} {:?}", v, w);
    v.sort_by(|a, b| b.cmp(a));
    println!("{:?}", v);
}

Result

[1, 2, 3] ["fig", "pear", "apple"]
[3, 2, 1]

Exercise

Sort by key.

w.sort_by(f)

Quiz Test

Does sort need mut?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.