HashMap::new() / insert() / get()
| Since: | Rust 1.0(2015) |
|---|
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;
let mut map: HashMap<String, i32> = HashMap::new();
// Add key-value pairs (overwrites if the key already exists).
map.insert("user_a".to_string(), 90);
map.insert("user_c".to_string(), 85);
// Retrieve a value by key (returns Option<&V>).
let val = map.get("user_a"); // Some(&90)
let val = map.get("xxx"); // None
// You can also use the index operator (panics if key is absent).
let val = &map["user_a"]; // &90
Method Reference
| Method | Description |
|---|---|
| HashMap::new() | Creates an empty HashMap. |
| HashMap::with_capacity(n) | Creates a HashMap with pre-allocated memory for n elements. |
| map.insert(key, value) | Inserts a key-value pair. Returns Some(old_value) if the key already existed. |
| map.get(&key) | Returns the value for the key as Option<&V>. |
| map.get_mut(&key) | Returns the value as Option<&mut V> (mutable). |
| map[&key] | Returns a reference to the value (panics if key is absent). |
| map.len() | Returns the number of entries. |
| map.is_empty() | Returns true if the HashMap is empty. |
| map.clear() | Removes all entries. |
Sample Code
sample_hashmap_new_insert_get.rs
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert("user_a".to_string(), 90);
scores.insert("user_c".to_string(), 85);
scores.insert("user_e".to_string(), 92);
println!("scores: {:?}", scores);
println!("len: {}", scores.len());
// Retrieve a value with get() (returns an Option).
match scores.get("user_a") {
Some(score) => println!("user_a's score: {}", score),
None => println!("user_a not found"),
}
// Use if let for concise access.
if let Some(score) = scores.get("user_c") {
println!("user_c's score: {}", score);
}
// Handle None from get().
let masaoka = scores.get("user_b");
println!("user_b's score: {:?}", masaoka); // None
// Use unwrap_or() to provide a default value.
let score = scores.get("user_b").unwrap_or(&0);
println!("user_b's score (default 0): {}", score);
// Modify a value with get_mut().
if let Some(score) = scores.get_mut("user_a") {
*score += 5; // 90 → 95
}
println!("user_a updated: {:?}", scores.get("user_a"));
// insert() returns the old value.
let old = scores.insert("user_c".to_string(), 100);
println!("user_c'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);
// A HashMap with string values.
let label_map: HashMap<String, String> = vec![
("user_a".to_string(), "alpha".to_string()),
("user_c".to_string(), "gamma".to_string()),
("user_e".to_string(), "epsilon".to_string()),
].into_iter().collect();
println!("user_a's label: {:?}", label_map.get("user_a"));
}
Compile with the following command:
rustc hashmap_new_insert_get.rs
./hashmap_new_insert_get
scores: {"user_a": 90, "user_c": 85, "user_e": 92}
len: 3
user_a's score: 90
user_c's score: 85
user_b's score: None
user_b's score (default 0): 0
user_a updated: Some(95)
user_c's old score: Some(85)
team_map: {"Japan": 3, "USA": 5, "Germany": 2}
user_a's label: Some("alpha")
Common Mistakes
Common mistake 1: panicking with index syntax when the key is absent
Using map["key"] panics if the key does not exist. Use get() and handle the Option to avoid panics.
use std::collections::HashMap;
fn main() {
let mut map: HashMap<String, i32> = HashMap::new();
map.insert("user_a".to_string(), 90);
// Panics: key does not exist
// let score = map["user_e"]; // panic!
}
The same logic can also be written as:
use std::collections::HashMap;
fn main() {
let mut map: HashMap<String, i32> = HashMap::new();
map.insert("user_a".to_string(), 90);
// Safe: handle the Option returned by get()
match map.get("user_e") {
Some(score) => println!("score: {}", score),
None => println!("not found"),
}
let score = map.get("user_e").unwrap_or(&0);
println!("score (default 0): {}", score);
}
Common mistake 2: forgetting that get() returns a reference (&V)
get() returns Option<&V>. When comparing values, you are working with a reference, not the value directly.
use std::collections::HashMap;
fn main() {
let mut map: HashMap<String, i32> = HashMap::new();
map.insert("user_c".to_string(), 85);
// get() returns Option<&i32> — a reference
if let Some(&score) = map.get("user_c") {
if score > 80 {
println!("high score: {}", score);
}
}
// Or dereference explicitly
if let Some(score) = map.get("user_c") {
if *score > 80 {
println!("high score: {}", *score);
}
}
}
Overview
HashMap does not guarantee insertion order, so the output order may vary for the same map. Use BTreeMap if you need a stable order.
In Rust, you can pass a &str as the key when searching a HashMap with String keys (thanks to the Borrow trait). This lets you write map.get("user_a") using a string literal.
The index operator (map["key"]) panics if the key is absent. Always use get() and handle the Option for safe access.
For key existence checks, removal, 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.