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}");
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
1. Leo (95)
2. Mia (82)
3. Zoe (82)
4. Ben (67)
average: 81.5

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज