In Go, the for
loop is a versatile construct used to iterate over a range of values, such as numbers, collections, or strings. It allows you to execute a block of code repeatedly based on a condition. Here are some examples of for
loops in Go:
- Loop with initialization, condition, and post statement:
for i := 0; i < 5; i++ {
fmt.Println(i)
}
In this example, the loop initializes i
to 0, continues as long as i
is less than 5, and increments i
by 1 in each iteration. It will print the numbers from 0 to 4.
- Loop with a condition:
i := 0
for i < 5 {
fmt.Println(i)
i++
}
In this example, the loop continues as long as i
is less than 5. It prints the numbers from 0 to 4. The initialization and post statements are outside the loop, and you manually update the loop variable i
inside the loop body.
- Infinite loop with break statement:
i := 0
for {
fmt.Println(i)
i++
if i >= 5 {
break
}
}
This example creates an infinite loop by omitting the condition from the for
statement. It prints the numbers from 0 to 4, and the loop is terminated using the break
statement when i
becomes greater than or equal to 5.
- Looping over an array or slice:
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Println("Index:", index, "Value:", value)
}
In this example, the range
keyword is used to iterate over the numbers
slice. It assigns the index and value of each element to the variables index
and value
respectively. It prints the index and value of each element in the slice.
The for
loop in Go provides flexibility and various ways to control the iteration. You can use it to perform tasks such as iterating over a range of values, processing collections, or implementing repetitive logic.