【发布时间】:2023-01-28 04:05:26
【问题描述】:
这是对 niveaus 的最高抱怨,但我解决了 rustlings 课程中的一项任务,我相信这不是最佳解决方案 - 甚至不是一个好的解决方案。
任务:https://github.com/rust-lang/rustlings/blob/main/exercises/hashmaps/hashmaps3.rs
我的解决方案(只有相关位):
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();
let team_1 = scores.entry(team_1_name.clone()).or_insert(Team {
name: team_1_name.clone(),
goals_scored: 0,
goals_conceded: 0,
});
team_1.goals_scored += team_1_score;
team_1.goals_conceded += team_2_score;
let team_2 = scores.entry(team_2_name.clone()).or_insert(Team {
name: team_2_name.clone(),
goals_scored: 0,
goals_conceded: 0,
});
team_2.goals_scored += team_2_score;
team_2.goals_conceded += team_1_score;
}
scores
}
我的问题是,我在 .entry() 方法中克隆字符串(两次!),也在 Team 结构中。我尝试不使用它,但它不起作用(借用东西)并使用 & 但它不高兴,因为它期望 String - 而不是 &String。
【问题讨论】: