GO Tutorial



LOOPS IN GO


Loops in Go

Loops help you execute a block of code repeatedly until a condition is met. Go has only one looping construct: the for loop, but it can be used in different ways to achieve all looping needs.

Basic for Loop

The classic for loop has three components: initialization, condition, and post statement.

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

while-style Loop

Go does not have a separate while loop, but you can use for like a while.

count := 0
for count < 5 {
    fmt.Println("Count is", count)
    count++
}
  

Infinite Loop

To create an infinite loop, omit the condition in the for statement.

for {
    // This loop will run forever unless broken out
    fmt.Println("Infinite loop")
    break  // use break to exit the loop
}
  

Looping Over Arrays and Slices with range

The range keyword makes it easy to loop over elements in arrays, slices, maps, and strings.

numbers := []int{10, 20, 30, 40}

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

Using break and continue

- break exits the loop immediately.
- continue skips the current iteration and moves to the next.

for i := 0; i < 10; i++ {
    if i == 5 {
        break  // exit loop when i is 5
    }
    if i%2 == 0 {
        continue  // skip even numbers
    }
    fmt.Println(i)  // prints only odd numbers less than 5
}
  

Summary

  • Go uses for as the only loop, versatile for many use cases.
  • Use the classic for with initialization, condition, and post statement for counted loops.
  • Use for condition { } to loop like a while.
  • for { } creates an infinite loop.
  • range makes iterating over collections clean and easy.
  • break and continue control loop execution flow.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review