0
0
Goprogramming~3 mins

Why Nested loops in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could check every possible pair without writing endless repeated steps?

The Scenario

Imagine you have a list of friends and a list of their favorite fruits. You want to find all possible friend-fruit pairs by checking each friend with each fruit manually.

The Problem

Doing this by hand means writing many repeated steps, which is slow and easy to mess up. If you add more friends or fruits, the work grows fast and becomes confusing.

The Solution

Nested loops let you automate this by running one loop inside another. This way, you can quickly check every friend with every fruit without writing repetitive code.

Before vs After
Before
fmt.Println("Alice likes Apple")
fmt.Println("Alice likes Banana")
fmt.Println("Bob likes Apple")
fmt.Println("Bob likes Banana")
After
friends := []string{"Alice", "Bob"}
fruits := []string{"Apple", "Banana"}
for _, friend := range friends {
    for _, fruit := range fruits {
        fmt.Printf("%s likes %s\n", friend, fruit)
    }
}
What It Enables

Nested loops let you handle complex combinations easily, saving time and avoiding mistakes.

Real Life Example

Checking every seat in a theater for availability by rows and columns uses nested loops to cover all seats efficiently.

Key Takeaways

Manual pairing is slow and error-prone.

Nested loops automate checking all combinations.

This makes your code cleaner and faster.