How to satisfy clippy

I'm checking my code through cargo clippy. it shows a warning below:

warning: usage of `contains_key` followed by `insert` on a `HashMap`
39 | /         if !orderbooks.contains_key(&inst) {
40 | |             orderbooks.insert(inst, T::new_update(update));
41 | |             return Ok(());
42 | |         }
   | |_________^ consider using `orderbooks.entry(inst)`
   = note: `#[warn(clippy::map_entry)]` on by default
   = help: for further information visit

warning: 1 warning emitted

    Finished dev [unoptimized + debuginfo] target(s) in 23.72s

As you can see, I need the function to return if i choose to add an entry. chaining entry with or_inserts in this case seems cant help much. Is there anyway more idiomatic?

Entry is an enum that you can match against in the normal fashion, and its variants contain values that support operations like insert. The methods like or_insert are just there for greater convenience. Here's what Clippy is trying to tell you to do:

use std::collections::hash_map::Entry;
if let Entry::Vacant(e) = orderbooks.entry(inst) {
    return Ok(());

This is different from your original code because it does not look up inst twice (good) but it unconditionally consumes inst (possibly bad). On nightly you can use the hash_raw_entry feature to get access to raw_entry_mut. But if you don't want to use nightly, you're stuck with either doing the double lookup (and ignore/silence Clippy) or cloning inst.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.