Go – Loops Overview
Estimated reading: 3 minutes 269 views

Go Nested For Loop – Iterate Over Multi-Dimensional Data in Go (2025 Guide)

Introduction – What Are Nested For Loops in Go?

A nested for loop in Go means placing one for loop inside another. This is commonly used for multi-dimensional arrays, matrix traversal, nested iteration, or grid-based logic in CLI tools, games, or computations.

In this section, you’ll learn:

  • How to write nested for loops in Go
  • Iterate through 2D slices (matrices)
  • Use control flow (break, continue, labels) in nested loops
  • Best practices to avoid deep nesting pitfalls

Basic Syntax – Go Nested For Loop

for i := 0; i < n; i++ {
    for j := 0; j < m; j++ {
        // inner loop block
    }
}

Example – Simple Nested Loop

for i := 1; i <= 3; i++ {
    for j := 1; j <= 2; j++ {
        fmt.Printf("i=%d, j=%d\n", i, j)
    }
}

Output:

i=1, j=1  
i=1, j=2  
i=2, j=1  
i=2, j=2  
i=3, j=1  
i=3, j=2

The outer loop runs 3 times; for each outer iteration, the inner loop runs 2 times.


Example – 2D Slice (Matrix Traversal)

matrix := [][]int{
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9},
}

for i := 0; i < len(matrix); i++ {
    for j := 0; j < len(matrix[i]); j++ {
        fmt.Printf("%d ", matrix[i][j])
    }
    fmt.Println()
}

Output:

1 2 3  
4 5 6  
7 8 9

Nested range Loop Over 2D Slice

for i, row := range matrix {
    for j, val := range row {
        fmt.Printf("matrix[%d][%d] = %d\n", i, j, val)
    }
}

Output:

matrix[0][0] = 1  
matrix[0][1] = 2  
matrix[0][2] = 3  
matrix[1][0] = 4  
matrix[1][1] = 5  
matrix[1][2] = 6  
matrix[2][0] = 7  
matrix[2][1] = 8  
matrix[2][2] = 9

Using range is cleaner and safer when iterating over slices or arrays.


Using Labels with Nested Loops

Break out of both loops using a label:

Outer:
for i := 1; i <= 3; i++ {
    for j := 1; j <= 3; j++ {
        if i*j > 4 {
            break Outer
        }
        fmt.Println(i, j)
    }
}

Output:

1 1  
1 2  
1 3  
2 1

As soon as i*j > 4, the program exits both loops.


Common Mistakes to Avoid

MistakeFix
Forgetting inner loop reset logicEnsure correct counter initialization
Infinite loop from wrong conditionCheck both loop conditions carefully
Too deep nestingRefactor into helper functions

Best Practices

  • Use range for collections to simplify loop logic
  • Name labels meaningfully for readability (Outer, Exit)
  • Avoid nesting more than 2–3 levels—extract logic into functions
  • Use blank identifiers (_) when loop variables aren’t used

Summary – Recap & Next Steps

Nested for loops are essential for handling multi-dimensional data or cross-iteration logic in Go. Whether you’re working with matrices, combinations, or nested tasks, Go offers clean syntax and safe control mechanisms.

Key Takeaways:

  • Nest for loops to handle multi-dimensional structures
  • Use range for readable and idiomatic iteration
  • Use break, continue, and labels to control complex loops
  • Avoid excessive nesting—refactor when possible

Next: Learn about Go Functions to encapsulate logic and make nested operations reusable.


FAQs – Go Nested For Loop

Can I use range inside a nested for loop?
Yes. You can use nested range loops to iterate over 2D slices or maps.

How do I break out of both loops at once?
Use a labeled break, e.g., break Outer.

Is it okay to nest more than 2 loops?
It’s possible, but not recommended. Consider breaking logic into smaller functions for clarity.

Can I use continue in a nested loop?
Yes. continue applies to the current loop it’s in. Use labels if needed to skip outer loops.

Are nested loops slow in Go?
Not inherently. But performance depends on the volume of iterations and algorithm efficiency.


Share Now :
Share

Go Nested For Loop

Or Copy Link

CONTENTS
Scroll to Top