"Alice\"), 10);
scores.insert(String::from(\"Bob\"), 20);
// From vectors (requires tuples)
let teams = vec![(String::from(\"Red\"), 100), (String::from(\"Blue\"), 50)];
let map: HashMap<_, _> = teams.into_iter().collect();
}
Accessing Values
use std::collections::HashMap;
fnmain() {
letmut map = HashMap::new();
map.insert(String::from(\"color\"), String::from(\"blue\"));
// get() returns Option
if let Some(value) = map.get(\"color\") {
println!(\"Color: {}\", value);
}
// get_mut() for mutable access
if let Some(value) = map.get_mut(\"color\") {
*value = String::from(\"red\");
}
// Check existence
if map.contains_key(\"color\") {
println!(\"Color exists\");
}
}
Iteration
use std::collections::HashMap;
fnmain() {
letmut map = HashMap::new();
map.insert(\"a\", 1);
map.insert(\"b\", 2);
// Iterate over references
for (key, value) in &map {
println!(\"{}: {}\", key, value);
}
// Iterate with mutable values
for value in map.values_mut() {
*value += 1;
}
// Iterate keys only
for key in map.keys() {
println!(\"Key: {}\", key);
}
}
Entry API or Updating Values
use std::collections::HashMap;
fnmain() {
letmut map = HashMap::new();
map.insert(String::from(\"a\"), 1);
// Update if exists, insert if not
*map.entry(String::from(\"a\")).or_insert(0) += 1;
*map.entry(String::from(\"b\")).or_insert(0) += 1;
println!(\"{:?}\", map); // {\"a\": 2, \"b\": 1}
}
Practical Example: Word Frequency
use std::collections::HashMap;
fncount_words(text: &str) -> HashMap<&str, i32> {
letmut counts = HashMap::new();
forwordin text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
counts
}
fnmain() {
lettext = \"hello world hello rust world\";
let counts = count_words(text);
for (word, count) in counts {
println!(\"{}: {}\", word, count);
}
}
Key Requirements
Keys must implement:
Eq: Equality comparison
Hash: Hashability
Most common types already implement these: String, integers, booleans.
Performance
Average case: O(1) insertion, lookup, deletion
Worst case: O(n) (hash collisions)
Good hash functions make worst case rare
HashMap Downsides
Unordered: No guaranteed iteration order
Slower than BTreeMap for ordered operations
More memory overhead than vectors
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities