Chapter 27: Rust HashMap

Rust HashMap (HashMap<K, V>), which is the most commonly used key-value store in Rust programs.

When you need to associate keys with values (like city → population, username → score, word → count), you almost always reach for HashMap. It’s fast for lookups, insertions, and deletions (average O(1) time), and it’s completely memory-safe thanks to Rust’s ownership and borrowing rules.

Let me explain Rust HashMap like your personal teacher sitting next to you with code open: slowly, step by step, with lots of runnable examples, everyday Hyderabad analogies (phone contacts, biryani orders, traffic signals), comparisons to other languages, and all the important patterns & gotchas.

1. What is HashMap<K, V>? (The Core Idea)

HashMap<K, V> = hash table that stores key-value pairs.

  • Keys (K) must implement Eq + Hash (most types do: String, &str, i32, bool, custom structs…)
  • Values (V) can be anything
  • Keys are unique — inserting same key twice overwrites the old value
  • Unordered (iteration order is unpredictable — use BTreeMap if you need sorted keys)
  • Stored on the heap, grows automatically
  • Very fast average-case lookups, inserts, removes

Analogy: Think of your phone contacts app.

  • Key = person’s name (“Rahul”, “Priya”)
  • Value = phone number / details
  • You can quickly find Priya’s number (fast lookup)
  • You can’t have two “Priya” entries with different numbers (unique keys)
  • Adding a new friend is fast, even when you have thousands of contacts

2. Creating a HashMap – All Common Ways

Rust
  • Always mut if you plan to insert/remove
  • Keys are owned by the map (usually String, not &str)

3. Basic Operations – Insert, Get, Remove

Rust
  • insert(key, value) → returns old value if key existed (Option<V>)
  • get(key) → Option<&V> (immutable borrow)
  • remove(key) → Option<V> (takes ownership of value)

4. The Entry API – Most Idiomatic Way (Very Important!)

The .entry() method is the recommended way for “get or insert” patterns.

Rust

Other useful entry patterns:

Rust

5. Iterating Over HashMap

Rust
  • &map → (&K, &V) pairs
  • &mut map → (&K, &mut V)
  • map → (K, V) (consumes map)

6. Common Gotchas & Best Practices (2026 Style)

  • Prefer String keys over &str in the map itself (owns the data)
  • Use &str for lookup: map.get(“Hyderabad”) works via Deref coercion
  • Don’t use HashMap when you need sorted keys → use BTreeMap
  • For very small maps → consider [(K,V); N] array + linear search
  • Capacity: use .with_capacity(n) or .reserve(n) when you know approximate size
  • Avoid cloning keys unnecessarily — use .entry() patterns

Practice Challenge for Today

Create cargo new rust_hashmap and try:

  1. HashMap<String, u32> city → population (add 5 Telangana cities)
  2. Use .entry() to count words in a sentence about Hyderabad food
  3. Function that takes &HashMap<String, i32> and prints top 3 scores
  4. Add 100 random key-value pairs → check len() vs capacity()

Want next?

  • BTreeMap vs HashMap (when order matters)?
  • HashMap with custom keys (need Hash + Eq)?
  • Iterators on HashMap (.map, .filter, .collect)?
  • Or structs containing HashMap + ownership/borrowing?

Just tell me — your Rust teacher is right here with you! 🦀🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *