Avatar ·

Efficient search and insertion in HashMap in Rust: how to avoid double hashing?

Hello, colleagues! I'm starting to learn Rust and encountered a typical task: I need to update a value in HashMap if the key exists, or insert a new pair if the key doesn't exist. The problem is that I'm doing this in two steps: first checking for the key's presence via contains_key(), and then inserting or modifying the value. But, as I understand, this leads to double hashing — once during the check and a second time during insertion. This seems inefficient, especially for large dictionaries.

\n\n

Here's my current code:

\n
use std::collections::HashMap;\n\nfn update_or_insert(map: &mut HashMap<String, i32>, key: &str, value: i32) {\n    if map.contains_key(key) {\n        // Update existing value\n        if let Some(val) = map.get_mut(key) {