📖 Scenario: Imagine you want to build a simple phone book app that stores names and phone numbers. To do this efficiently, you decide to create your own HashMap from scratch in Rust, which will help you quickly find a phone number by a person's name.
🎯 Goal: You will build a basic HashMap in Rust that can store key-value pairs (names and phone numbers), handle collisions using chaining, and allow inserting and retrieving values.
📋 What You'll Learn
Create a struct called HashMap with a vector of buckets
Implement a simple hash function for string keys
Add an insert method to add key-value pairs
Add a get method to retrieve values by key
Handle collisions by storing multiple entries in each bucket
💡 Why This Matters
🌍 Real World
HashMaps are used everywhere to store and quickly find data by keys, like phone books, caches, and databases.
💼 Career
Understanding how HashMaps work under the hood helps you write efficient code and debug performance issues in real software projects.
Progress0 / 4 steps
1
Create the basic HashMap structure
Create a struct called HashMap with a field buckets that is a Vec of vectors holding tuples of (String, String). Initialize buckets with 5 empty vectors inside the new function.
DSA Rust
Hint
Use vec![Vec::new(); 5] to create 5 empty vectors inside the buckets vector.
2
Add a simple hash function
Inside the impl HashMap block, add a private method hash that takes a &str key and returns a usize. The method should sum the bytes of the key and return the sum modulo the number of buckets (5).
DSA Rust
Hint
Use key.bytes() and fold to sum the byte values of the string.
3
Implement the insert method
Add a public method insert that takes &mut self, a String key, and a String value. Use the hash method to find the bucket index. Append the (key, value) tuple to the bucket vector. If the key already exists in the bucket, update its value instead of adding a new tuple.
DSA Rust
Hint
Loop over the bucket vector with for pair in &mut self.buckets[index] to check for existing keys.
4
Implement the get method and print results
Add a public method get that takes &self and a &str key, and returns an Option<&String>. Use the hash method to find the bucket index. Search the bucket for the key and return Some(&value) if found, otherwise None. Then, create a main function that creates a HashMap, inserts these entries: ("Alice", "1234"), ("Bob", "5678"), ("Charlie", "9012"), and prints the phone number for "Bob" and "Eve" (which is not inserted).
DSA Rust
Hint
Use Option and match to handle the result of get. Print the value if found, or a not found message otherwise.
Practice
(1/5)
1. What is the main purpose of a HashMap in data structures?
easy
A. To store elements in a queue-like manner
B. To store elements in sorted order
C. To store key-value pairs for fast lookup
D. To store elements in a stack-like manner
Solution
Step 1: Understand HashMap functionality
A HashMap stores data as key-value pairs, allowing quick access by key.
Step 2: Compare with other data structures
Unlike stacks or queues, HashMaps do not maintain order but focus on fast lookup.
Final Answer:
To store key-value pairs for fast lookup -> Option C
Quick Check:
HashMap = key-value fast access [OK]
Hint: HashMap = fast key-value storage [OK]
Common Mistakes:
Confusing HashMap with sorted structures
Thinking HashMap stores elements in order
Mixing HashMap with stack or queue behavior
2. Which of the following is the correct Rust syntax to create an empty HashMap from scratch?
easy
A. let map = HashMap::empty();
B. let map = new HashMap();
C. let map = HashMap();
D. let map = HashMap::new();
Solution
Step 1: Recall Rust HashMap creation syntax
Rust uses HashMap::new() to create an empty HashMap.
Step 2: Check other options for Rust correctness
Options B, C, and D are not valid Rust syntax for HashMap creation.
Final Answer:
let map = HashMap::new(); -> Option D
Quick Check:
Rust HashMap empty = HashMap::new() [OK]
Hint: Use HashMap::new() to create empty map [OK]
Common Mistakes:
Using constructor syntax like new HashMap()
Calling HashMap() without ::new()
Using non-existent methods like empty()
3. Consider this simplified Rust code snippet for a custom HashMap insert method:
Before inserting, search the bucket's vector for the key to update value or append if not found.
Step 3: Evaluate options
Store key-value pairs in a vector at each bucket; on insert, search vector for key to update or append correctly describes this approach; others ignore key checks or hashing.
Final Answer:
Store key-value pairs in a vector at each bucket; on insert, search vector for key to update or append -> Option A
Quick Check:
Separate chaining + key check = efficient insert [OK]
Hint: Search bucket vector for key before insert [OK]
Common Mistakes:
Ignoring key existence in bucket
Not using hashing for bucket selection
Replacing bucket data blindly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.