Rust HashMap
Key-value storage for efficient data retrieval
🗂️ What is a HashMap?
HashMap is Rust's key-value storage collection that lets you store and retrieve data using unique keys. Perfect for creating dictionaries, caches, and lookup tables with fast access times.
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert("Alice", 100);
scores.insert("Bob", 85);
HashMap Operations
Insert
Add key-value pairs
map.insert("key", "value");
Get
Retrieve values by key
map.get("key")
Remove
Delete key-value pairs
map.remove("key")
Iterate
Loop through all pairs
for (k, v) in ↦
🔹 Creating and Using HashMap
Here's how to create and use a HashMap in Rust:
use std::collections::HashMap;
fn main() {
// Create a new HashMap
let mut student_grades = HashMap::new();
// Insert some data
student_grades.insert("Alice", 95);
student_grades.insert("Bob", 87);
student_grades.insert("Charlie", 92);
// Get a value
match student_grades.get("Alice") {
Some(grade) => println!("Alice's grade: {}", grade),
None => println!("Alice not found"),
}
// Check if key exists
if student_grades.contains_key("Bob") {
println!("Bob is in the class");
}
}
Output:
Alice's grade: 95
Bob is in the class
Bob is in the class
🔹 HashMap Methods
Common HashMap methods for data manipulation:
use std::collections::HashMap;
fn main() {
let mut inventory = HashMap::new();
// Insert items
inventory.insert("apples", 50);
inventory.insert("bananas", 30);
// Update or insert
inventory.entry("oranges").or_insert(25);
inventory.entry("apples").or_insert(0); // Won't change existing value
// Update existing value
*inventory.entry("bananas").or_insert(0) += 10;
// Print all items
for (item, count) in &inventory {
println!("{}: {}", item, count);
}
// Remove an item
inventory.remove("apples");
println!("Items after removal: {}", inventory.len());
}
Output:
apples: 50
bananas: 40
oranges: 25
Items after removal: 2
bananas: 40
oranges: 25
Items after removal: 2
🔹 Creating HashMap from Data
Different ways to initialize HashMap with data:
use std::collections::HashMap;
fn main() {
// From vectors
let teams = vec!["Blue", "Yellow"];
let scores = vec![10, 50];
let mut game_scores: HashMap<_, _> = teams.iter().zip(scores.iter()).collect();
// Using collect on iterator
let data = [("red", "#FF0000"), ("green", "#00FF00"), ("blue", "#0000FF")];
let colors: HashMap<&str, &str> = data.iter().cloned().collect();
// Print colors
for (name, hex) in &colors {
println!("{}: {}", name, hex);
}
}
Output:
red: #FF0000
green: #00FF00
blue: #0000FF
green: #00FF00
blue: #0000FF