Hey everyone, I am new to Rust and programming in general. Nearly finished the Rust book and am working through the Rustlings exercises. I just completed hashmaps3, after a bit of a struggle and would love some feedback on my code and approach.
I ended up implementing an add() method on the struct and calling it in add_modify()'s closure body.
I also removed the name from the struct definition as it's not really necessary and eliminates the need to clone it a second time.
use std::collections::HashMap;
// A structure to store team name and its goal details.
#[derive(Debug)]
struct Team {
goals_scored: u8,
goals_conceded: u8,
}
// create a method on Team struct that also adding fields together.
impl Team {
pub fn add(&mut self, conceded: u8, scored: u8) -> Team {
self.goals_conceded = self.goals_conceded + conceded;
self.goals_scored = self.goals_scored + scored;
return Team {goals_conceded: self.goals_conceded, goals_scored: self.goals_scored}
}
}
fn build_scores_table(results: String) -> HashMap<String, Team> {
// The name of the team is the key and its associated struct is the value.
let mut scores: HashMap<String, Team> = HashMap::new();
for r in results.lines() {
let v: Vec<&str> = r.split(',').collect();
let team_1_name = v[0].to_string();
let team_1_score: u8 = v[2].parse().unwrap();
let team_2_name = v[1].to_string();
let team_2_score: u8 = v[3].parse().unwrap();
scores.entry(team_1_name.clone())
// if entry exists add fields to fields.
.and_modify(|t| { t.add(team_2_score, team_1_score);})
.or_insert(Team{goals_scored: team_1_score, goals_conceded: team_2_score});
scores.entry(team_2_name.clone())
.and_modify(|t| { t.add(team_1_score, team_2_score);})
.or_insert(Team{goals_scored: team_2_score, goals_conceded: team_1_score});
};
return scores
}
Any feedback/tips would be great, thank you