Loop Structures in Go
Loop Structures in Go
Go (Golang) provides several loop structures to handle different iteration scenarios. The primary loop structure in Go is the for loop, which is versatile and can be used in various forms to mimic other loop types. Below is an overview of loop structures in Go, along with examples.
1. Basic for Loop
The basic for loop in Go is to the for loop in other C-style languages. It consists of an initialization, a condition, and a post-statement, all separated by semicolons.
Syntax:
go
for initialization; condition; post-statement {
// Code to be executed in each iteration
}
Example:
go
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Printf("Iteration: %d\n", i)
}
}
This loop initializes i to 0, checks if i is less than 5, and increments i by 1 after each iteration. It prints the iteration number until i reaches 5.
2. for Loop Without Conditions (Infinite Loop)
If you omit the condition in a for loop, it becomes an infinite loop. You can break out of it using a break statement or a return statement.
Syntax:
go
for {
// Code to be executed indefinitely until a break or return
}
Example:
go
package main
import (
"fmt"
"time"
func main() {
count := 0
for {
fmt.Printf("Count: %d\n", count)