Avatar ·

How to efficiently perform search and insert in HashMap in Rust?

Greetings, colleagues! I'm new to Rust and encountered a problem when working with `HashMap`. I need to implement a frequency dictionary: read lines from a text file, count the occurrences of each word, and output the top 10. In other languages (e.g., Python), I would simply do `dict[word] = dict.get(word, 0) + 1`. But in Rust it's more complicated. Here's my code that works but seems terribly inefficient: ```rust use std::collections::HashMap; fn main() { let text = "hello world hello rust rust rust"; let mut map: HashMap<&str, u32> = HashMap::new(); for word in text.split_whitespace() { if map.contains_key(word) { let count = map.get(word).unwrap(); map.insert(word, count + 1); } else { map.insert(word, 1); ```