Rust Data Structures
Estimated reading: 3 minutes 30 views

🦀 Rust – HashMap: Efficient Key-Value Storage with Safety and Power

🧲 Introduction – Why Learn HashMap in Rust?

When you need to associate keys with values (like usernames to emails, or words to counts), the HashMap is your go-to tool. Rust’s HashMap is part of the std::collections module and offers constant-time lookups, ownership-aware insertion, and safe access patterns.

🎯 In this guide, you’ll learn:

  • How to create and use HashMap
  • Insertion, update, and retrieval techniques
  • How ownership and borrowing apply to keys and values
  • Practical examples with real output and safety insights

🧰 Creating a HashMap

🔹 Code Example:

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Alice", 50);
    scores.insert("Bob", 75);
    println!("{:?}", scores);
}

🧠 Explanation:

  • HashMap::new() creates an empty map
  • .insert(key, value) adds key-value pairs
  • HashMap must be declared mut to insert

📤 Output:

{"Alice": 50, "Bob": 75}

⚠️ Order is not guaranteed in HashMap


🔄 Accessing Values with .get()

🔹 Code Example:

fn main() {
    let mut users = HashMap::new();
    users.insert("admin", "root");

    match users.get("admin") {
        Some(role) => println!("Role: {}", role),
        None => println!("User not found"),
    }
}

🧠 Explanation:

  • .get(key) returns Option<&V>
  • Safe access avoids panics on missing keys

📤 Output:

Role: root

🧩 Looping Through Key-Value Pairs

🔹 Code Example:

fn main() {
    let mut capitals = HashMap::new();
    capitals.insert("France", "Paris");
    capitals.insert("Japan", "Tokyo");

    for (country, city) in &capitals {
        println!("{} => {}", country, city);
    }
}

📤 Output:

France => Paris
Japan => Tokyo

📝 Updating and Overwriting Values

🔹 Code Example:

fn main() {
    let mut data = HashMap::new();
    data.insert("key1", 10);
    data.insert("key1", 20); // Overwrites previous value

    println!("{:?}", data);
}

📤 Output:

{"key1": 20}

🔍 Conditional Insert with entry()

🔹 Code Example:

use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.entry("Alice").or_insert(50);
    scores.entry("Alice").or_insert(100); // Skipped

    println!("{:?}", scores);
}

🧠 Explanation:

  • .entry().or_insert() only inserts if key doesn’t exist
  • Useful for caching, counting, or default initialization

📤 Output:

{"Alice": 50}

🔒 Ownership and HashMap

Rust moves both the key and the value into the HashMap.

🔹 Code Example:

fn main() {
    let name = String::from("user1");
    let mut map = HashMap::new();
    map.insert(name, "active");
    // println!("{}", name); // ❌ Error: name was moved
}

✅ Use .clone() if you want to keep using the original variable after insertion.


🔄 Common Operations Summary

OperationMethodBehavior
Insert.insert(k, v)Moves key and value into map
Get.get(k)Returns Option<&V>
Update.insert() with same keyOverwrites old value
Insert if absent.entry(k).or_insert(v)Inserts only if key does not exist
Remove.remove(k)Deletes key-value pair and returns Option

📌 Summary – Recap & Next Steps

Rust’s HashMap gives you powerful, flexible key-value storage—backed by ownership guarantees and safe access. Whether you’re counting frequencies or caching results, it’s a must-have tool in your Rust toolbox.

🔍 Key Takeaways:

  • HashMap stores key-value pairs with unique keys
  • All insertions move ownership unless cloned
  • .get() returns an Option, avoiding panics
  • Use .entry() for conditional inserts and mutation

⚙️ Next: Explore Rust – Structs to define your own custom data types and models.


❓FAQs


Why is my variable inaccessible after inserting into a HashMap?
✅ Because ownership is moved. Use .clone() if you need to retain access.


How do I safely check if a key exists?
✅ Use .get() to return Option<&V> or .contains_key() to check existence.


Does HashMap preserve insertion order?
❌ No. Standard HashMap is unordered. Use IndexMap (from the indexmap crate) if order matters.


Can I use complex types as keys?
✅ Yes, but the key type must implement Eq and Hash.


Share Now :

Leave a Reply

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

Share

Rust – HashMap

Or Copy Link

CONTENTS
Scroll to Top