The for loop in Go is a fundamental control structure that allows you to execute a block of code repeatedly. It's highly versatile and ubiquitous in most Go programs. We'll explore its use from basic scenarios to more advanced implementations.
Basic Usage of For Loop
The syntax of a basic for loop in Go is simple. Here's a straightforward example:
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
In this example, the loop will print the numbers 0 through 4. The loop contains three main components: initialization (i := 0), condition (i < 5), and post-expression (i++).
Intermediate Usage: Loop without Condition
The for loop can also be used without any condition, functioning as an infinite loop if not terminated by any internal logic. Consider this example:
package main
import "fmt"
func main() {
i := 0
for {
fmt.Println(i)
i++
if i == 5 {
break
}
}
}
Here, the loop will continue indefinitely until it hits the break statement when i equals 5.
Advanced Usage: Nested Loops and Ranges
Nested loops are another powerful use of the for loop. They allow you to perform complex tasks, such as iterating over multi-dimensional data structures:
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {
fmt.Printf("i = %d, j = %d\n", i, j)
}
}
}
This code will print pairs of (i, j) from (1, 1) to (3, 3).
Go also provides a convenient way to loop over slices, arrays, maps, or channels using the range keyword:
package main
import "fmt"
func main() {
numbers := []int{10, 20, 30, 40}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
Each iteration of the loop gives you the index and value of an element of the slice numbers.
Conclusion
The for loop is a versatile tool in Go that covers all the looping needs through its different forms. From simple loops to nested loops and iteration over collections, Go's for loop keeps your code efficient and clear.