0
0
Goprogramming~3 mins

Why Iterating over maps in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could find any friend's number instantly without flipping through pages?

The Scenario

Imagine you have a list of friends and their phone numbers written on paper. To find a number, you have to look through each name one by one until you find the right one.

The Problem

This manual search is slow and tiring, especially if the list is long. You might skip a name or get confused, making mistakes easy and frustrating.

The Solution

Using a map lets you jump straight to the friend's number by their name, like having an instant phonebook. Iterating over maps helps you quickly check all entries without missing any.

Before vs After
Before
for i := 0; i < len(names); i++ {
    if names[i] == target {
        fmt.Println(numbers[i])
    }
}
After
for name, number := range phoneBook {
    fmt.Println(name, number)
}
What It Enables

It makes handling and exploring collections of paired data fast, simple, and error-free.

Real Life Example

Think of a contact app that shows all your friends' names and numbers instantly, letting you scroll through or search easily.

Key Takeaways

Manual searching through lists is slow and error-prone.

Maps let you access data by keys instantly.

Iterating over maps helps you process all key-value pairs efficiently.