rust-lang / rust-lang/rust-clippy

Clippy fix makes breaking change on warning: usage of `contains_key` followed by `insert` on a `HashMap`

Open
#13,649 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

Clippy attempts to fix the warning: usage of contains_key followed by insert on a HashMap
and creates a borrow after move.

Original:

let name = format!("{}/{}", sensor_driver.namespace, sensor_driver.function);
if sensor_drivers.contains_key(&name) {
    res.error(format!("Duplicate sensor driver {} in drivers file.", name));
} else {
    sensor_drivers.insert(name, sensor_driver);
}

Clippy Fixed:

let name = format!("{}/{}", sensor_driver.namespace, sensor_driver.function);
if let std::collections::hash_map::Entry::Vacant(e) = sensor_drivers.entry(name) {
  e.insert(sensor_driver);
} else {
  res.error(format!("Duplicate sensor driver {} in drivers file.", name));
}

The Clippy generated code results in name being moved by HashMap::Entry before being borrowed by format!.

Version

rustc 1.81.0 (eeb90cda1 2024-09-04)
binary: rustc
commit-hash: eeb90cda1969383f56a2637cbd3037bdf598841c
commit-date: 2024-09-04
host: aarch64-apple-darwin
release: 1.81.0
LLVM version: 18.1.7

Additional Labels

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Locate the Clippy lint that detects contains_key followed by insert, then reproduce the issue with the Rust snippet in the report. Trace the generated HashMap::Entry suggestion and add a regression test showing that the suggested code does not borrow name after it has been moved; done means the fix compiles without the reported borrow-after-move error.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.