Rust 연습 문제
Sort Structs in Rust: Student Ranking
Sort a vector of structs by score and name with sort_by, then compute the average.
배울 내용
- 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.
핵심 포인트
b.cmp(a)sorts from high to low.- then breaks ties by name.
- 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 리뷰를 받을 수 있습니다.
- 선택한 키로 정렬하기 실행 중에 고른 비교자로 사람을 이름이나 나이순으로 정렬하고 동점은 일관되게 처리합니다. 쉬움
- Tournament Standings Rank teams from match records. 보통