Loops in Go
Loops in Go are used to repeat a block of code multiple times. The Go
programming language has only one looping construct, the for
loop, but it can
be used in various ways.
Basic For Loop
The basic for
loop has three components separated by semicolons:
1for init; condition; post {
2 // code to execute
3}
For as a While Loop
The for
loop can also be used as a while loop by omitting the init and post
statements:
1for condition {
2 // code to execute
3}
Infinite For Loop
An infinite loop runs forever unless it is stopped by a break statement or a
return from the enclosing function:
1for {
2 // code to execute
3}
Looping Over Collections
You can loop over elements in a slice or map using the range form of the for
loop:
1for index, value := range collection {
2 // code to execute
3}
Conclusion
Understanding loops in Go is essential for performing repetitive tasks
efficiently. The for
loop, with its various forms, provides a powerful tool
for iteration in Go programs.
Hint
Go code will not run if you have unused variables. Use _
to indicate that the
variable is required, but you will not be using it.