Rust 練習問題

Sort Structs in Rust: Student Ranking

Sort a vector of structs by score and name with sort_by, then compute the average.

  • 初級
  • 約3分で読めます
  • 実行できるサンプル 1 件
学べること
  • sort_by with a closure
  • then for tie breaks
  • Average with iterators
Ranking
Leo95
Mia82
Zoe82
Ben67
Mia comes before Zoe because the scores are equal.

Sort by score, then by name

Real data is usually a list of records. Sort the students by score from high to low, break ties by name, and print the ranking.

sort_by takes a closure that compares two students. b.score.cmp(&a.score) sorts from high to low, and then falls back to the name when the scores are equal. The average converts the sum to f64 so the division keeps its fraction.

重要なポイント

  1. b.cmp(a) sorts from high to low.
  2. then breaks ties by name.
  3. Convert to f64 before dividing.

実行できる Rust のサンプル

Rust
コードを実行 →
main.rs
struct Student {
    name: &'static str,
    score: u32,
}

fn main() {
    let mut students = vec![
        Student { name: "Mia", score: 82 },
        Student { name: "Leo", score: 95 },
        Student { name: "Zoe", score: 82 },
        Student { name: "Ben", score: 67 },
    ];

    students.sort_by(|a, b| b.score.cmp(&a.score).then(a.name.cmp(b.name)));
    for (rank, student) in students.iter().enumerate() {
        println!("{}. {} ({})", rank + 1, student.name, student.score);
    }

    let average = students.iter().map(|s| s.score).sum::<u32>() as f64 / students.len() as f64;
    println!("average: {average:.1}");
}
この例の実行ボタンを作成 実行結果
1. Leo (95)
2. Mia (82)
3. Zoe (82)
4. Ben (67)
average: 81.5

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ