Loops in Go

List Topics
February 15, 2025
No Comments
4 min read

Loops are an essential part of programming that allow executing a block of code multiple times. In Go, the only loop available is the for loop, but it can be used in different ways to achieve the functionality of while and do-while loops found in other languages.

1. Basic Syntax of for Loop

Go
for initialization; condition; increment {
    // Code to execute
}

🔹 Key Points:
✅ Initialization: Variable is initialized before the loop starts.
✅ Condition: The loop runs as long as the condition is true.
✅ Increment/Decrement: Controls how the loop variable updates.

2. Simple for Loop Example

Go
package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Println("Iteration:", i)
    }
}

🔹 Output:

Bash
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

👉 Explanation:

  • i := 1 → The loop starts with i = 1.
  • i <= 5 → The loop runs as long as i is ≤ 5.
  • i++ → i is incremented by 1 after each iteration.

3. Using for as a While Loop

In Go, the for loop can also be used like a while loop by omitting the initialization and increment parts.

Go
package main

import "fmt"

func main() {
    i := 1
    for i <= 5 {
        fmt.Println("Value of i:", i)
        i++
    }
}

🔹 Output:

Bash
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5

👉 Explanation:

  • No initialization inside for → i is declared before the loop.
  • No increment inside for → i++ is manually written inside the loop.

4. Infinite Loop in Go (for without condition)

If a for loop has no condition, it runs forever unless explicitly stopped with break.

Go
package main

import "fmt"

func main() {
    i := 1
    for {
        fmt.Println("Running... Iteration:", i)
        i++
        if i > 5 {
            break
        }
    }
}

🔹 Output:

Bash
Running... Iteration: 1
Running... Iteration: 2
Running... Iteration: 3
Running... Iteration: 4
Running... Iteration: 5

👉 Explanation:

  • No condition → The loop runs indefinitely.
  • if i > 5 { break } → Stops the loop when i > 5.

5. Using break to Exit a Loop

The break statement is used to exit a loop immediately, regardless of the condition.

Go
package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i == 5 {
            fmt.Println("Stopping loop at:", i)
            break
        }
        fmt.Println("Iteration:", i)
    }
}

🔹 Output:

Bash
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Stopping loop at: 5

👉 Explanation:

  • When i == 5, the break statement stops the loop.

6. Using continue to Skip an Iteration

The continue statement skips the current iteration and moves to the next one.

Go
package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i == 3 {
            fmt.Println("Skipping iteration:", i)
            continue
        }
        fmt.Println("Iteration:", i)
    }
}

🔹 Output:

Bash
Iteration: 1
Iteration: 2
Skipping iteration: 3
Iteration: 4
Iteration: 5

👉 Explanation:

  • When i == 3, continue skips the iteration, and the loop moves to i = 4.

7. Nested Loops (Loop Inside Another Loop)

A nested loop is a loop inside another loop.

Go
package main

import "fmt"

func main() {
    for i := 1; i <= 3; i++ {
        for j := 1; j <= 3; j++ {
            fmt.Printf("(%d, %d) ", i, j)
        }
        fmt.Println()
    }
}

🔹 Output:

Bash
(1, 1) (1, 2) (1, 3) 
(2, 1) (2, 2) (2, 3) 
(3, 1) (3, 2) (3, 3)

👉 Explanation:

  • Outer loop (i) runs 3 times → Controls rows.
  • Inner loop (j) runs 3 times per row → Controls columns.

8. Looping Through an Array/Slice Using for range

Go provides the range keyword to iterate over slices, arrays, and maps.

Go
package main

import "fmt"

func main() {
    nums := []int{10, 20, 30, 40, 50}

    for index, value := range nums {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

🔹 Output:

Bash
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50

👉 Explanation:

  • index → Position in the slice.
  • value → Value at that position.

🔹 If only values are needed, _ is used to ignore index:

Go
for _, value := range nums {
    fmt.Println(value)
}

Conclusion

Loop TypeDescription
forStandard loop with initialization, condition, and increment.
for condition {}Behaves like a while loop.
for {}Infinite loop (requires break to stop).
breakExits the loop immediately.
continueSkips the current iteration.
for rangeIterates over arrays, slices, maps, and strings.

🚀 Go only has the for loop, but it is powerful enough to replace while and do-while loops!

Go-āϤ⧇ āϞ⧁āĻĒ āϕ⧀?

āϞ⧁āĻĒ āĻŦā§āϝāĻŦāĻšāĻžāϰ āĻ•āϰ⧇ āĻāĻ•āϟāĻŋ āϕ⧋āĻĄ āĻŦā§āϞāĻ• āĻŦāĻžāϰāĻŦāĻžāϰ āϚāĻžāϞāĻžāύ⧋ āϝāĻžāϝāĻŧ, āϝāϤāĻ•ā§āώāĻŖ āύāĻž āύāĻŋāĻ°ā§āĻĻāĻŋāĻˇā§āϟ āĻļāĻ°ā§āϤ āĻŽāĻŋāĻĨā§āϝāĻž āĻšāϝāĻŧāĨ¤

1. āϏāĻžāϧāĻžāϰāĻŖ for āϞ⧁āĻĒ

Go
for i := 1; i <= 5; i++ {
    fmt.Println(i)
}

✅ while āϞ⧁āĻĒ⧇āϰ āĻŽāϤ āĻŦā§āϝāĻŦāĻšāĻžāϰ

Go
i := 1
for i <= 5 {
    fmt.Println(i)
    i++
}

✅ āχāύāĻĢāĻŋāύāĻŋāϟāĻŋ āϞ⧁āĻĒ (for {})

Go
for {
    fmt.Println("āϚāϞāϤ⧇ āĻĨāĻžāĻ•āĻŦ⧇...")
}

✅ break āĻāĻŦāĻ‚ continue

Go
for i := 1; i <= 5; i++ {
    if i == 3 {
        continue // 3 āĻŦāĻžāĻĻ āĻĻ⧇āĻŦ⧇
    }
    fmt.Println(i)
}

Š2025 Linux Bangla | Developed & Maintaind by Linux Bangla.