RRust By Example
intermediateCollections

Sorting Vectors

Sort vectors with sort, sort_by, and sort_unstable.

Sorting Vectors

Sort vectors with sort, sort_by, and sort_unstable.

Difficulty

Intermediate

Code

rust
fn main() {
    let mut nums = vec![5, 2, 8, 1, 9, 3];
    nums.sort();
    println!("sorted: {:?}", nums);

    let mut words = vec!["banana", "apple", "cherry"];
    words.sort_by(|a, b| a.len().cmp(&b.len()));
    println!("by length: {:?}", words);

    // custom struct sorting
    #[derive(Debug)]
    struct Student { name: String, grade: u32 }

    let mut students = vec![
        Student { name: "Alice".into(), grade: 90 },
        Student { name: "Bob".into(), grade: 85 },
        Student { name: "Charlie".into(), grade: 95 },
    ];
    students.sort_by(|a, b| b.grade.cmp(&a.grade));
    println!("by grade desc: {:?}", students);
}

Explanation

This example demonstrates how to use sorting vectors in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the collections category to build a complete understanding of this topic.

More Collections Examples