capypad
0 day streak
rust / beginner
Snippet

HashMap: Key-Value Storage

HashMap<K, V> stores key-value pairs with O(1) average lookup time. Use entry API to efficiently handle missing keys. The get method returns Option<&V>, forcing you to handle missing keys. HashMap requires the K type to implement Eq and Hash traits.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
use std::collections::HashMap;
 
fn main() {
// Creating an empty HashMap
let mut scores: HashMap<&str, i32> = HashMap::new();
// Inserting key-value pairs
scores.insert("Alice", 100);
scores.insert("Bob", 85);
scores.insert("Charlie", 92);
// Using get with Option handling
match scores.get("Alice") {
Some(score) => println!("Alice's score: {}", score),
None => println!("Alice not found"),
}
// Using entry API for conditional insertion
let entry = scores.entry("Diana").or_insert(0);
*entry += 10;
// Iterating over key-value pairs
for (name, score) in &scores {
println!("{}: {}", name, score);
}
// Updating a value based on existing one
let name = "Bob";
if let Some(score) = scores.get_mut(name) {
*score += 5;
}
println!("Bob's updated score: {}", scores[name]);
}
Breakdown
1
use std::collections::HashMap;
Imports HashMap from the standard library collections module
2
let mut scores: HashMap<&str, i32> = HashMap::new();
Creates an empty HashMap with &str keys and i32 values
3
scores.insert("Alice", 100);
Inserts a key-value pair into the HashMap
4
scores.entry("Diana").or_insert(0);
Entry API: inserts 0 if key doesn't exist, returns mutable reference to existing or new value
5
for (name, score) in &scores
Iterating over references to key-value pairs without consuming the HashMap