Rust HashMap
🦀 Rust HashMap (HashMap<K, V>)
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:
🔹 2. Creating a HashMap
▶️ Empty HashMap
▶️ With Initial Values
🔹 3. Accessing Values
▶️ Using get() (Safe way ✅)
✔ Returns Option<&V>
▶️ Using unwrap() (Not recommended for beginners)
⚠️ Panics if key does not exist.
🔹 4. Iterating Over a HashMap
✔ Order is not guaranteed
🔹 5. Updating Values
▶️ Overwrite Existing Value
▶️ Insert Only If Key Doesn’t Exist (entry API)
✔ Very common
✔ Very powerful
🔹 6. Modifying Values
🔹 7. Removing Elements
🔹 8. HashMap and Ownership (IMPORTANT)
▶️ Ownership Moves Into HashMap
✔ Use references if needed:
🔹 9. HashMap with String Keys
🔹 10. Checking Key Existence
🔹 11. HashMap Length
🔹 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()blindlyForgetting 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
