I'm learning rust using rustlings. I was trying to implement a solution in a functional way (rustlings only asked for the imperative way). I'm running into the following compiler error and haven't been able to figure this out since 2 hours. Please help
Progress: [############################>-------------------------------] 45/94
! Compiling of exercises/hashmaps/hashmaps3.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
--> exercises/hashmaps/hashmaps3.rs:94:28
|
94 | .and_modify(|team| Team {
| ____________________________^
95 | | name: team.name.to_string(),
96 | | goals_scored: team.goals_scored+team_from_iter.goals_scored,
97 | | goals_conceded: team.goals_conceded+team_from_iter.goals_conceded,
98 | | })
| |_________^ expected `()`, found struct `Team`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
This is the set of lines the compiler has an issue with
.and_modify(|team| Team {
name: team.name.to_string(),
goals_scored: team.goals_scored+team_from_iter.goals_scored,
goals_conceded: team.goals_conceded+team_from_iter.goals_conceded,
})
pub fn and_modify<F>(self, f: F) -> Self where F: FnOnce(&mut V),
and_modify
's argument has the type FnOnce(&mut V)
. This is a function that takes a single argument of type &mut V
and returns nothing. (If it were returning something it would have a signature like FnOnce(&V) -> V
instead.)
Concretely, you're receiving a mutable Team
object that's already in the hash map and you're expected to modify it in place. Instead of constructing a brand new Team
you should update the team that you're being passed. Something like this, say:
.and_modify(|team| {
team.goals_scored += team_from_iter.goals_scored;
team.goals_conceded += team_from_iter.goals_conceded;
})
Notice how this modifies team
in place and doesn't return anything.