Module 2: Maps (The Key Rack)
๐ Module 2: Maps
Course ID: GO-106
Subject: The Key Rack
A Map allows you to store data in Key-Value pairs. It is the most efficient way to find something instantly without searching through a list.
๐๏ธ Step 1: Instant Retrieval
๐งฉ The Analogy: The Hotel Key Rack
- The Key: The Room Number (e.g., โ301โ).
- The Value: The physical key to that room.
- If you ask for room โ301,โ the receptionist doesnโt check every room in the hotel. They look at the Key Rack and grab it instantly.
๐๏ธ Step 2: In Code
// 1. Create a map of [Name] to [Age]
ages := make(map[string]int)
// 2. Add some data
ages["Alice"] = 25
ages["Bob"] = 30
// 3. Get data back
aliceAge := ages["Alice"]๐๏ธ Step 3: Checking if a Key Exists
In Go, if you ask for a key that isnโt there, you get a Zero Value (Module 2). But what if the value actually is zero? We use the โComma OKโ pattern.
val, ok := ages["Charlie"]
if ok {
fmt.Println("Found Charlie!", val)
} else {
fmt.Println("Charlie doesn't exist.")
}๐ฅ Module 2 Review
- Map: A Key-Value dictionary.
- make(): The required tool to build a new map.
- OK Pattern: How we check if a key actually exists.
:::tip Senior Tip Maps in Go are NOT sorted. If you print a map twice, the order might change! If you need a specific order, you must sort the keys separately. :::