I am new to Rust Programming. This is from rustlings/hashmaps/hashmaps3.
struct Team {
goals_scored: u8,
goals_conceded: u8,
}
impl Team {
fn new() -> Self {
Team {
goals_scored: 0,
goals_conceded: 0,
}
}
}
fn build_scores_table(results: String) -> HashMap<String, Team> {
let mut scores: HashMap<String, Team> = HashMap::new();
let zero_team = Team::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 =
let Team { goals_scored, goals_conceded } = scores.get(&team_1_name)
.unwrap_or(&zero_team);
let new_score = Team {
goals_scored: goals_scored + team_1_score,
goals_conceded: goals_conceded + team_2_score,
};
scores.insert(team_1_name, new_score);
let Team { goals_scored, goals_conceded } = scores.get(&team_2_name)
.unwrap_or(&zero_team);
let new_score = Team {
goals_scored: goals_scored + team_2_score,
goals_conceded: goals_conceded + team_1_score,
};
scores.insert(team_2_name, new_score);
}
scores
}
This code solves the issues, but I feel like I am missing some chunks of understanding here. And I have some questions:
- What is the meaning of
zero_team
, Is it like a singleton here? - Am I shadowing
goals_scored
andgoals_conceded
or am I redefining them? - What is the most idiomatic way to do this? How would you solve the problem?