Skip to main content
Go Language Fundamentals for Beginners to Advanced
CHAPTER 11 Beginner

Maps in Go

Updated: May 17, 2026
5 min read

# 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.*

go
1234567891011121314151617
package main
import "fmt"

func main() {
    // Creates a map where the Key is a string (Name), and Value is an int (Age)
    ages := make(map[string]int)

    // Inserting Data
    ages["Alice"] = 28
    ages["Bob"] = 35

    // Retrieving Data
    fmt.Println("Alice is", ages["Alice"]) // Prints 28
    
    // Updating Data
    ages["Bob"] = 36 
}

Short Initialization:

go
12345
capitals := map[string]string{
    "USA":    "Washington D.C.",
    "Japan":  "Tokyo",
    "France": "Paris", // Trailing comma is REQUIRED in Go!
}

4. The "Comma Ok" Idiom (Safe Lookup)

What happens if you ask for a key that does not exist in the map?
go
1
fmt.Println(ages["Charlie"])

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.

go
12345678
// 'ok' will be true if "Charlie" exists, false if he doesn't
age, ok := ages["Charlie"]

if ok {
    fmt.Println("Charlie's age is", age)
} else {
    fmt.Println("Charlie was not found in the database.")
}

5. Iterating and Deleting

You iterate over a Map using the for ... 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!
go
1234567
// Iterating
for key, value := range capitals {
    fmt.Printf("The capital of %s is %s\n", key, value)
}

// Deleting a key
delete(capitals, "France") 

6. Mini Project: Student Record Manager

go
123456789101112131415161718
package main
import "fmt"

func main() {
    grades := make(map[string]string)
    grades["John"] = "A"
    grades["Emma"] = "B"

    // Safe Lookup Functionality
    searchName := "Emma"
    grade, exists := grades[searchName]
    
    if exists {
        fmt.Printf("%s's grade: %s\n", searchName, grade)
    } else {
        fmt.Printf("Student %s not found.\n", searchName)
    }
}

7. Common Mistakes

  • Nil Map Panic: If you declare a map with var myMap map[string]int but forget to initialize it with make(), it is a nil map. If you try to add data to a nil map (myMap["Bob"] = 5), the program will crash instantly!
  • Assuming Order: Relying on the for loop 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. 1. Create a Map representing a grocery store inventory. Keys are string (item names), Values are float64 (prices).
  1. 2. Add "Apple" ($1.20) and "Milk" ($2.50).
  1. 3. Use delete() to remove "Milk".
  1. 4. Use the "comma ok" idiom to safely check if "Bread" exists in the map.

10. MCQs with Answers & Explanations

Question 1

What is the fundamental structure of a Map?

Question 2

What is the primary advantage of a Map over a Slice?

Question 3

Which function is required to initialize an empty map before adding data?

Question 4

What happens if you try to add data to a nil (uninitialized) map?

Question 5

If you lookup a key that doesn't exist (val := myMap["Missing"]), what does Go return?

Question 6

What is the "comma ok" idiom (val, ok := map[key]) used for?

Question 7

What data type is the ok variable in the "comma ok" idiom?

Question 8

Which built-in function removes a Key-Value pair from a map?

Q9. Are Maps in Go sorted alphabetically by default? a) Yes b) No, they are strictly unordered Answer: b) No, they are strictly unordered.

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. 1. What happens when you read a missing key from a Go map, and how does this differ from Python?
  1. 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 the val, ok := map[key] idiom is essential for writing safe, bug-free backend logic.

13. Next Chapter Recommendation

We've been using strings extensively, but text handling in Go has some unique quirks due to its strict adherence to modern web standards. In Chapter 12: Strings and Runes, we will discover how Go manages UTF-8 text and what a "Rune" actually is.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·