Skip to content

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

  1. Map: A Key-Value dictionary.
  2. make(): The required tool to build a new map.
  3. 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. :::