Skip to content

Warn for overwriting HashMap entry #11978

Open
@SeseMueller

Description

@SeseMueller

What it does

Inserting on a HashMap on a key that is already contained overwrites the value that was at that location.
If the return value of insert (Option<T>; what was previously there) is not used, that value is lost.
While it is practically impossible to warn for all cases where this might occur, a few might be caught.
I suggest checking for an insert (or get_mut().unwrap()) followed by another insert which throws away the return value, while there weren't any reads on the HashMap in between.

Advantage

  • Catch the loss of a value due to overwriting it
  • Also useful for Hashmaps that map to complex types that may be mutated in-place

Drawbacks

In some situations overwriting the old value is exactly the plan and this warn might have false positives in these kinds of situations.
This also opens the discussion whether HashMap::insert's result should be must use, where the ease of use stands against potential errors like the loss of data as explained above.

Example

    let mut test = HashMap::new();
    test.insert(5, vec![1,2,3]); // Or get_mut if the values is already contained: test.get_mut(5).unwrap().push(4)
    test.insert(5, vec![]); // Return value not used

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions