Skip to content
Discussion options

You must be logged in to vote

To make it work in Rust, there are 2 solutions:

Solution 1 (intermediate but efficient)

You need to add the lifetime annotation 'a to tell the compiler that team_name won't be dropped while scores exists.
&str is a pointer to some string in memory. If you drop that string in memory while you still use the pointer as a key in the hash map, then that key would be a dangling pointer.

fn add_single_team_game_result<'a>( scores: &mut HashMap<&'a str, TeamScores>, team_name: &'a str, scored: u8, conceded: u8, ) { let team = scores.entry(team_name).or_default(); team.goals_scored += scored; team.goals_conceded += conceded; }

Then you need to pass &mut scores in the fu…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by mo8it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants