capypad
0 day streak
rust / beginner
Snippet

HashMap for Key-Value Storage

HashMap stores key-value pairs with O(1) average lookup time. Use .get() to safely retrieve values as Option<&V>. The .entry() API allows inserting only if the key doesn't exist using or_insert().

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::collections::HashMap;
 
fn main() {
let mut scores = HashMap::new();
scores.insert(String::from("Alice"), 100);
scores.insert(String::from("Bob"), 85);
println!("Alice's score: {:?}", scores.get("Alice"));
scores.entry(String::from("Charlie")).or_insert(90);
for (name, score) in &scores {
println!("{}: {}", name, score);
}
}
Breakdown
1
use std::collections::HashMap;
HashMap must be imported from std::collections
2
scores.insert(String::from("Alice"), 100);
Insert requires owned String keys, not &str literals
3
scores.get("Alice")
get() returns Option<&V>, None if key missing
4
.entry(String::from("Charlie")).or_insert(90)
entry() returns Entry enum; or_insert sets default if absent