Maps in Go
# CHAPTER 11
Maps in Go
1. Introduction
Imagine you have a Slice of 1,000,000 users, and you need to find the phone number for "Alice". You would have to loop through the Slice one by one until you find her, which takes time (O(N) time complexity). A Map (known as a Dictionary in Python/C# or an Object in JavaScript) stores data in Key-Value pairs. Looking up Alice's phone number by using her name as the "Key" is virtually instantaneous (O(1) time complexity).2. Learning Objectives
By the end of this chapter, you will be able to:-
Declare and initialize a Map using
make().
- Insert and update Key-Value pairs.
- Retrieve data from a Map.
- Safely check if a key exists (The "comma ok" idiom).
-
Delete entries using
delete().
3. Creating and Using a Map
A map requires two data types: one for the Key, and one for the Value. Syntax:map[KeyType]ValueType
*Note: You MUST use the make() function (or short declaration) to initialize a map before adding data to it.*
Short Initialization:
4. The "Comma Ok" Idiom (Safe Lookup)
What happens if you ask for a key that does not exist in the map?In many languages, this crashes the program. In Go, it returns the Zero Value of the value type (in this case, 0 for an int).
But wait! What if Charlie is actually in the map and his age is exactly 0 (a newborn)? How do we know if the key is missing, or if the value is just 0?
Go provides the "comma ok" idiom. Looking up a map can return TWO values: the result, and a boolean indicating if the key actually exists.
5. Iterating and Deleting
You iterate over a Map using thefor ... range loop, just like slices.
Important: Maps in Go are UNORDERED. If you iterate through a map 5 times, it might print the keys in a different order every time!
6. Mini Project: Student Record Manager
7. Common Mistakes
-
Nil Map Panic: If you declare a map with
var myMap map[string]intbut forget to initialize it withmake(), it is anilmap. If you try to add data to anilmap (myMap["Bob"] = 5), the program will crash instantly!
-
Assuming Order: Relying on the
forloop to print map keys in alphabetical order. Maps are hash tables; their order is intentionally randomized by Go for security reasons.
8. Best Practices
-
Always use "comma ok": Never assume a key exists. Always use
val, ok := myMap[key]to prevent logic bugs caused by default Zero Values.
9. Exercises
- 1. Create a Map representing a grocery store inventory. Keys are string (item names), Values are float64 (prices).
- 2. Add "Apple" ($1.20) and "Milk" ($2.50).
-
3.
Use
delete()to remove "Milk".
- 4. Use the "comma ok" idiom to safely check if "Bread" exists in the map.
10. MCQs with Answers & Explanations
What is the fundamental structure of a Map?
What is the primary advantage of a Map over a Slice?
Which function is required to initialize an empty map before adding data?
What happens if you try to add data to a nil (uninitialized) map?
If you lookup a key that doesn't exist (val := myMap["Missing"]), what does Go return?
What is the "comma ok" idiom (val, ok := map[key]) used for?
What data type is the ok variable in the "comma ok" idiom?
Which built-in function removes a Key-Value pair from a map?
Q10. Can you use a Slice as a Key in a Map (e.g., map[[]int]string)?
a) Yes b) No
Answer: b) No. *Explanation: Map keys must be comparable (like strings, ints, or booleans). Slices cannot be compared with ==.*
11. Interview Preparation
Interview Questions:- 1. What happens when you read a missing key from a Go map, and how does this differ from Python?
- 2. Why does Go intentionally randomize map iteration order? (Answer: To prevent developers from accidentally writing code that relies on hash ordering, and to mitigate Hash DoS security attacks).
12. Summary
Maps are the ultimate tool for fast data retrieval. By storing data in Key-Value pairs, they provide instantaneous lookups. However, because Go returns "Zero Values" for missing keys, mastering theval, ok := map[key] idiom is essential for writing safe, bug-free backend logic.