如何在 Rust 中高效执行 HashMap 的查找与插入?
各位同行好!我是 Rust 新手,在使用 `HashMap` 时遇到了问题。我需要实现一个词频字典:从文本文件中读取字符串,统计每个单词的出现次数,并输出前 10 个。在其他语言(例如 Python)中,我只需使用 `dict[word] = dict.get(word, 0) + 1`。但在 Rust 中要复杂得多。
以下是我的代码,虽然能运行,但看起来效率极低:
```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);
}
}
println!("{:?}", map);
}
```
问题:
1. 对于每个单词,我进行了两次 `HashMap` 操作:先检查 `contains_key`,然后 `get`,再 `insert`。这看起来很浪费。