Rust HashMap

🦀 Rust HashMap (HashMap<K, V>)

A HashMap in Rust is a key–value data structure used to store data where:
  • Each key is unique

  • Each key maps to one value

  • Data is stored on the heap

  • Access is fast (average O(1))

HashMap is part of Rust’s standard collections.


🔹 1. Importing HashMap

HashMap is not in the prelude, so you must import it:

use std::collections::HashMap;

🔹 2. Creating a HashMap

▶️ Empty HashMap

use std::collections::HashMap;

fn main() {
let mut scores = HashMap::new();
}


▶️ With Initial Values

let mut scores = HashMap::new();

scores.insert("Math", 90);
scores.insert("Science", 95);


🔹 3. Accessing Values

▶️ Using get() (Safe way ✅)

match scores.get("Math") {
Some(score) => println!("{}", score),
None => println!("No score found"),
}

✔ Returns Option<&V>


▶️ Using unwrap() (Not recommended for beginners)

let score = scores.get("Math").unwrap();

⚠️ Panics if key does not exist.


🔹 4. Iterating Over a HashMap

for (key, value) in &scores {
println!("{}: {}", key, value);
}

✔ Order is not guaranteed


🔹 5. Updating Values

▶️ Overwrite Existing Value

scores.insert("Math", 100);

▶️ Insert Only If Key Doesn’t Exist (entry API)

scores.entry("English").or_insert(85);

✔ Very common
✔ Very powerful


🔹 6. Modifying Values

let score = scores.entry("Math").or_insert(0);
*score += 5;

🔹 7. Removing Elements

scores.remove("Science");

🔹 8. HashMap and Ownership (IMPORTANT)

▶️ Ownership Moves Into HashMap

let key = String::from("Rust");
let value = 2024;

let mut map = HashMap::new();
map.insert(key, value);

// println!("{}", key); ❌ ownership moved

✔ Use references if needed:

let key = String::from("Rust");
map.insert(&key, 2024);

🔹 9. HashMap with String Keys

let mut users = HashMap::new();

users.insert(String::from("Sanjit"), 22);
users.insert(String::from("Amit"), 25);


🔹 10. Checking Key Existence

if scores.contains_key("Math") {
println!("Math exists");
}

🔹 11. HashMap Length

println!("{}", scores.len());

🔹 12. Common HashMap Methods

Method Purpose
insert() Add/update value
get() Read value
remove() Delete entry
entry() Insert/update smartly
contains_key() Check key
len() Number of pairs
is_empty() Check empty

🔹 13. HashMap vs BTreeMap (Quick Idea)

Feature HashMap BTreeMap
Order No order Sorted
Speed Faster Slower
Use case General Ordered data

❌ Common Mistakes

  • Expecting ordered output

  • Using unwrap() blindly

  • Forgetting ownership moves

  • Modifying map while iterating incorrectly


🧠 Key Takeaways

  • HashMap stores key–value pairs

  • Keys must be unique

  • Access is fast

  • Order is not guaranteed

  • Ownership & borrowing rules apply

You may also like...