rust-clippy icon indicating copy to clipboard operation
rust-clippy copied to clipboard

map_entry with else if and hashmap produce uncompilable code

Open Freyskeyd opened this issue 1 year ago • 0 comments

Summary

The generated suggestion can't be compiled when using else if and a HashMap. I created a playground to reproduce the issue: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=acfee3c8c6ac5f68248d2317f17a1b46

Lint Name

map_entry

Reproducer

I tried this code:

        if self.pending_dial.contains_key(&peer_id) {
            println!("Key one");
        } else if peer_id != *self.swarm.local_peer_id() {
            println!("Key two");
            self.pending_dial.insert(peer_id, "sender".to_string());
        } else {
            println!("Else");
        }

I saw this happen:

warning: usage of `contains_key` followed by `insert` on a `HashMap`
  --> src/main.rs:35:9
   |
35 | /         if self.pending_dial.contains_key(&peer_id) {
36 | |             println!("Key one");
37 | |         } else if peer_id != *self.swarm.local_peer_id() {
38 | |             println!("Key two");
...  |
41 | |             println!("Else");
42 | |         }
   | |_________^
   |
note: the lint level is defined here
  --> src/main.rs:1:9
   |
1  | #![warn(clippy::map_entry)]
   |         ^^^^^^^^^^^^^^^^^
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#map_entry
help: try this
   |
35 ~         if let std::collections::hash_map::Entry::Vacant(e) = self.pending_dial.entry(peer_id) if peer_id != *self.swarm.local_peer_id() {
36 +             println!("Key two");
37 +             e.insert("sender".to_string());
38 +         } else {
39 +             println!("Else");
40 +         } else {
41 +             println!("Key one");
42 +         }
   |

I expected a compilation ready suggestion

Version

clippy: 0.1.64 (2022-08-07 d394408)
Rust: Stable channel version: 1.62.1

Additional Labels

No response

Freyskeyd avatar Aug 08 '22 14:08 Freyskeyd