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.
The classic for
loop has three components: initialization, condition, and post statement.
for i := 0; i < 5; i++ { fmt.Println("Iteration:", i) }
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++ }
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 }
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) }
- 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 }
for
as the only loop, versatile for many use cases.for
with initialization, condition, and post statement for counted loops.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.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!