Looking forward to the day I can solve something simple in Rust on my own in less than a half hour without help. I want to take a vector of Student instances and find the top three students in terms of their average score. I'm not able to determine from the error message what type it wants. Once that is solved, it will panic and I don't understand that either.
#[derive(Debug)]
struct Student {
name: String,
scores: Vec<i8>,
}
impl Student {
fn new(name: &str, scores: &[i8]) > Self {
Self {
name: name.to_string(),
scores: scores.to_vec(),
}
}
}
fn average(numbers: &[i8]) > f32 {
numbers.iter().sum::<i8>() as f32 / numbers.len() as f32
}
fn main() {
let mut students: Vec<Student> = vec![
Student::new("Alice", &[90, 75, 80]),
Student::new("Betty", &[85, 95, 80]),
Student::new("Claire", &[70, 80, 75]),
Student::new("Dina", &[95, 100, 90]),
Student::new("Elaine", &[75, 90, 10]),
];
students.sort_by(a, b {
let a_avg = average(&a.scores);
let b_avg = average(&b.scores);
a_avg.partial_cmp(&b_avg).unwrap()
});
println!("{:?}", students);
let top_students: &[Student] = students.iter().take(3).collect();
println!("{:?}", top_students);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0277]: a value of type `&[Student]` cannot be built from an iterator over elements of type `&Student`
> src/main.rs:34:60

34  let top_students: &[Student] = students.iter().take(3).collect();
 ^^^^^^^ value of type `&[Student]` cannot be built from `std::iter::Iterator<Item=&Student>`

= help: the trait `FromIterator<&Student>` is not implemented for `&[Student]`
error: aborting due to previous error
For more information about this error, try `rustc explain E0277`.
error: could not compile `playground`
To learn more, run the command again with verbose.