The for loop is a fundamental control structure in Go programming. It provides a powerful and flexible way to iterate over collections, perform repetitive tasks, and control program flow.
Go's for loop is versatile and can be used in several ways. The most common form is:
for initialization; condition; post {
// loop body
}
for i := 0; i < 5; i++ {
fmt.Println(i)
}
This loop prints numbers from 0 to 4.
Go doesn't have a while keyword, but you can use for to create a while-like loop:
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
Create an infinite loop using:
for {
// code to be executed
}
Use Go Break and Continue statements to control the loop's execution.
Iterate over arrays, slices, maps, or strings using the Go Range keyword:
fruits := []string{"apple", "banana", "cherry"}
for index, value := range fruits {
fmt.Printf("Index: %d, Value: %s\n", index, value)
}
For loops in Go are efficient, but consider these tips for optimal performance:
Master the for loop, and you'll have a powerful tool for controlling program flow in Go. Combined with other Go features like Go Goroutines and Go Channels, loops become even more powerful for concurrent programming.