Rust

Rust

Made by DeepSource

Audit required: Calling extend() on HashMap RS-A1009

Bug risk
Major

Using the extend() method on a HashMap overwrites the value associated with an existing key if it is present in the hash map being used to extend the original one. This may not be intentional, and can lead to unexpected behaviour of overriding values associated with existing keys in both HashMaps.

Consider revisiting this function call and ensure that the behaviour is as expected.

Bad practice

use std::collections::HashMap;

fn season_total_goals() {
    let mut goals_match1 = HashMap::from([("TeamA", 1), ("TeamB", 2)]);
    let goals_match2 = HashMap::from([("TeamB", 1), ("TeamD", 2)]);
    goals_match1.extend(goals_match2);

    assert_eq!(goals_match1.get("TeamB"), 3); // "TeamB" got overwritten by goals_match2
}

Recommended

use std::collections::HashMap;

fn season_total_goals() {
    let mut goals_match1 = HashMap::from([("TeamA", 1), ("TeamB", 2)]);
    let goals_match2 = HashMap::from([("TeamB", 1), ("TeamD", 2)]);
    for (team, score) in goals_match1 {
        if !goals_match1.contains(team) {
             goals_match1.insert(team, score);
        } else {
            goals_match1.get_mut(&team) += score;
        }
    }
    assert_eq!(goals_match1.get("TeamB"), 3); // "TeamB" scores correctly totalled
}