Loops in Go
Introduction to Loops
Loops are used to execute a block of code multiple times. In Go, loops are primarily handled using the for loop. Unlike other languages, Go does not have a separate while
or do-while
loop; instead, different variations of the for
loop are used.
Basic For Loop
The basic for
loop consists of three parts: initialization, condition, and increment/decrement.
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
fmt.Println("Iteration:", i)
}
}
This loop runs from 1
to 5
, printing each iteration.
For Loop as a While Loop
Go doesn’t have a separate while
loop; instead, a for
loop can be used as a while loop by omitting the initialization and increment.
package main
import "fmt"
func main() {
i := 1
for i <= 5 {
fmt.Println("Iteration:", i)
i++
}
}
This loop runs as long as the condition i <= 5
is true.
Infinite Loop
An infinite loop in Go is created using for
without a condition. This is useful for server processes or continuously running tasks.
package main
import "fmt"
func main() {
for {
fmt.Println("This is an infinite loop")
}
}
Note: To stop an infinite loop, use break
or ctrl + C
in the terminal.
Break and Continue
The break
statement exits a loop immediately, while continue
skips the current iteration and proceeds to the next.
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
if i == 3 {
continue // Skips iteration 3
}
fmt.Println(i)
if i == 4 {
break // Stops loop at 4
}
}
}
Here, iteration 3
is skipped using continue
, and the loop stops completely when i == 4
due to break
.
Conclusion
Loops are an essential part of programming, and Go provides a powerful for
loop that can be used in different ways. Whether it's a traditional loop, a while
-like loop, or an infinite loop, Go's simplicity makes iteration straightforward.
In the next lesson, we will explore Functions in Go, covering how to define, call, and return values from functions.