rust / beginner
Snippet
Working with HashMap Key-Value Storage
HashMap stores key-value pairs with O(1) average lookup time. The entry API is powerful for insertion-or-update patterns. or_insert returns a mutable reference to the value, allowing modification.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
use std::collections::HashMap;fn word_count(text: &str) -> HashMap<&str, i32> {let mut counts = HashMap::new();for word in text.split_whitespace() {let count = counts.entry(word).or_insert(0);*count += 1;}counts}fn main() {let sentence = "hello world hello rust hello";let frequencies = word_count(sentence);for (word, count) in &frequencies {println!("{}: {}", word, count);}}
Breakdown
1
counts.entry(word).or_insert(0)
Gets entry for key, inserts 0 if missing, returns mutable reference
2
*count += 1
Dereferences and increments the count
3
for (word, count) in &frequencies
Iterates over key-value pairs by borrowing