Chapter 47: Go Maps

1. What is a Map? (The Simplest Explanation)

A map is:

An unordered collection of key–value pairs You give it a key, it instantly gives you back the value (very fast lookup — average O(1))

Think of it as:

  • A dictionary (Python)
  • A hash map / HashMap (Java)
  • An object / associative array (JavaScript)
  • A phone book: name (key) → phone number (value)

In Go, maps are reference types (like slices, channels, functions) → they are nil by default and you must make or initialize them before using.

2. Creating a Map – All Realistic Ways

Go

Golden rule #1:

Never write to a nil map — always create it first with make() or literal.

3. Reading, Writing, Checking Existence, Deleting

Go

Very important idiom:

Go

This is the standard way to safely read from a map in Go.

4. Iterating Over a Map (for range)

Go

Important notes:

  • Order is random / undefined — every run may give different order
  • If you need sorted order → collect keys → sort them → loop over sorted keys
  • range gives copy of key & value — safe to modify value but not key

5. Common Real-World Patterns (You Will Use These Every Day)

Pattern 1: Counting occurrences

Go

Pattern 2: Fast lookup / existence check

Go

Pattern 3: Grouping data

Go

6. Important Rules & Gotchas

  • Nil map panic — most common beginner mistake → always initialize before writing
  • Maps are reference types → passing map to function = cheap header copy → modifications affect original
  • Keys must be comparable → allowed: int, string, bool, float, struct/array with comparable fields → not allowed: slice, map, function
  • No key of type interface{} (unless you use concrete type under interface)
  • Maps are not safe for concurrent writes → use sync.Mutex or sync.Map for concurrent access

7. Quick Practice – Try These

  1. Create a map[string]int that counts how many times each letter appears in “Hyderabad”
  2. Create map[string][]string → group friends by city
  3. Write a function that returns true if a key exists in a map
  4. Write a function that deletes all keys whose value < 10

Which pattern felt most useful for real programs?

Any part still confusing?

  • Why maps are unordered / random iteration?
  • How to make a map thread-safe?
  • Difference between nil map and empty map?
  • Or ready to move to methods (functions attached to structs) next?

Keep creating and looping over small maps — they are one of the most powerful tools for fast lookups and grouping in Go.

You’re progressing really fast — keep asking! 💪🇮🇳🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *