Bài tập Rust
Sort Structs in Rust: Student Ranking
Sort a vector of structs by score and name with sort_by, then compute the average.
Bạn sẽ học được gì
- sort_by with a closure
- then for tie breaks
- Average with iterators
Ranking
Leo95
Mia82
Zoe82
Ben67
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.
Những điểm quan trọng
b.cmp(a)sorts from high to low.- then breaks ties by name.
- Convert to f64 before dividing.
Ví dụ Rust chạy được
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.5Luyện tập
Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.
Bạn học xong bài này chưa?
Đánh dấu đã học để theo dõi tiến độ của bạn.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
Luyện tập với thử thách
Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.
- Sắp xếp theo khóa được chọn Sắp xếp mọi người theo tên hoặc theo tuổi bằng một comparer được chọn khi chạy, đồng thời phá vỡ các trường hợp bằng nhau một cách nhất quán. Dễ
- Tournament Standings Rank teams from match records. Trung bình