-
Notifications
You must be signed in to change notification settings - Fork 11k
Closed
Description
Hello, I am new with Rust!
Trying to solve the exercise like this:
let team1 = Team {goals_scored: 0, goals_conceded: 0};
let entry1 = scores.entry(team_1_name).or_insert(team1);
let team2 = Team {goals_scored: 0, goals_conceded: 0};
let entry2 = scores.entry(team_2_name).or_insert(team2);
entry1.goals_scored += team_1_score;
entry1.goals_conceded += team_2_score;
entry2.goals_scored += team_2_score;
entry2.goals_conceded += team_1_score;
produces the following error:
Compiling of exercises/hashmaps/hashmaps3.rs failed! Please try again. Here's the output:
error[E0499]: cannot borrow `scores` as mutable more than once at a time
--> exercises/hashmaps/hashmaps3.rs:46:22
|
43 | let entry1 = scores.entry(team_1_name).or_insert(team1);
| ------------------------- first mutable borrow occurs here
...
46 | let entry2 = scores.entry(team_2_name).or_insert(team2);
| ^^^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
47 |
48 | entry1.goals_scored += team_1_score;
| ----------------------------------- first borrow later used here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0499`.
which makes sense because I am borrowing 2 mutable references to scores entries. But when I permute the code like this
let team1 = Team {goals_scored: 0, goals_conceded: 0};
let entry1 = scores.entry(team_1_name).or_insert(team1);
entry1.goals_scored += team_1_score;
entry1.goals_conceded += team_2_score;
let team2 = Team {goals_scored: 0, goals_conceded: 0};
let entry2 = scores.entry(team_2_name).or_insert(team2);
entry2.goals_scored += team_2_score;
entry2.goals_conceded += team_1_score;
it compiles and pass the test.
Why this change make it work? I guess the compiler should not be able to distinguish that the entries are different by just looking at the code in both scenarios.
Metadata
Metadata
Assignees
Labels
No labels