HashMap::new() / insert() / get()
Rust's HashMap is a collection that stores key-value pairs. Use HashMap::new() to create one, insert() to add entries, and get() to retrieve values. You need to bring it into scope with use std::collections::HashMap;.
Syntax
use std::collections::HashMap;
// Creates an empty HashMap.
let mut map: HashMap<String, i32> = HashMap::new();
// Inserts key-value pairs (overwrites if the key already exists).
map.insert("apple".to_string(), 100);
map.insert("banana".to_string(), 200);
// Retrieves a value by key (returns Option<&V>).
let val = map.get("apple"); // Some(&100)
let val = map.get("xxx"); // None
// You can also use the index operator (panics if the key does not exist).
let val = &map["apple"]; // &100
Method List
| Method | Description |
|---|---|
| HashMap::new() | Creates an empty HashMap. |
| HashMap::with_capacity(n) | Creates a HashMap with memory pre-allocated for n elements. |
| map.insert(key, value) | Inserts a key-value pair. Returns the old value wrapped in Some if the key already existed. |
| map.get(&key) | Returns the value for a key as Option<&V>. |
| map.get_mut(&key) | Returns the value for a key as Option<&mut V> (allowing mutation). |
| map[&key] | Returns a reference to the value for a key (panics if the key does not exist). |
| map.len() | Returns the number of entries. |
| map.is_empty() | Returns whether the HashMap is empty. |
| map.clear() | Removes all entries. |
Sample Code
use std::collections::HashMap;
fn main() {
// Create a HashMap and add entries.
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert("Alice".to_string(), 90);
scores.insert("Bob".to_string(), 85);
scores.insert("Carol".to_string(), 92);
println!("scores: {:?}", scores);
println!("len: {}", scores.len());
// Use get() to retrieve a value (returns an Option type).
match scores.get("Alice") {
Some(score) => println!("Alice's score: {}", score),
None => println!("Alice not found"),
}
// Use if let for a more concise approach.
if let Some(score) = scores.get("Bob") {
println!("Bob's score: {}", score);
}
// Handle the case where get() returns None.
let dave = scores.get("Dave");
println!("Dave's score: {:?}", dave); // None
// Use unwrap_or() to provide a default value.
let score = scores.get("Dave").unwrap_or(&0);
println!("Dave's score (default 0): {}", score);
// Use get_mut() to modify a value.
if let Some(score) = scores.get_mut("Alice") {
*score += 5; // 90 → 95
}
println!("Alice after update: {:?}", scores.get("Alice"));
// insert() returns the old value.
let old = scores.insert("Bob".to_string(), 100);
println!("Bob's old score: {:?}", old); // Some(85)
// Build a HashMap from an iterable.
let teams = vec![
("Japan".to_string(), 3),
("USA".to_string(), 5),
("Germany".to_string(), 2),
];
let team_map: HashMap<String, i32> = teams.into_iter().collect();
println!("team_map: {:?}", team_map);
}
Notes
HashMap does not guarantee insertion order, so the output order may vary even for the same map. Use BTreeMap if you need ordered keys.
In Rust, you can search a HashMap with String keys using a &str value (thanks to the Borrow trait). This is why map.get("Alice") works with a string literal.
The index operator (map["key"]) panics if the key does not exist. Always use get() and handle the result as an Option for safe access.
For checking key existence, removing entries, and the entry API, see HashMap::contains_key() / remove() / entry(). For iteration, see HashMap::keys() / values() / iter().
If you find any errors or copyright issues, please contact us.