contains_key guarding an insert instead of the entry API

ID

rust.maintainability.map_entry

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Inefficient Api Usage

Language

Rust

Description

Reports a map lookup with contains_key that only decides whether to insert the same key, which is what the entry API expresses in a single call.

Rationale

The pair hashes and probes the map twice for one logical operation. It also splits the invariant across two statements, so the key used to test and the key used to insert can drift apart in a later edit without the compiler noticing. entry binds the two together and hands back the slot it has already found.

The following code illustrates the pattern detected by this rule:

use std::collections::HashMap;
pub fn register(sessions: &mut HashMap<String, u32>, key: String, ttl: u32) {
    // FLAGGED: contains_key guarding an insert instead of the entry API
    if !sessions.contains_key(&key) {
        sessions.insert(key, ttl);
    }
}

Remediation

Use map.entry(key).or_insert(value), or or_insert_with(|| value) when the value is expensive to build and or_default() when it is the type’s default. For the if/else spelling, entry also gives and_modify(…​).or_insert(…​).

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved