Ejercicios de Rust
Sort Structs in Rust: Student Ranking
Sort a vector of structs by score and name with sort_by, then compute the average.
Lo que aprenderás
- 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.
Puntos clave
b.cmp(a)sorts from high to low.- then breaks ties by name.
- Convert to f64 before dividing.
Ejemplo ejecutable de 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.5Practica
Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.
¿Terminaste esta lección?
Márcala como aprendida para seguir tu progreso.
Tu progreso está guardado en este navegador Inicia sesión para conservarlo en todos tus dispositivos.
Practica con un reto
Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.
- Ordenar por una clave elegida Ordena a las personas por nombre o por edad con un comparador elegido en tiempo de ejecución, resolviendo los empates de forma consistente. Fácil
- Tournament Standings Rank teams from match records. Intermedio