Go for Loop
In Go, the for
loop is used to execute a block of code repeatedly for a fixed number of times or as long as a specified condition is true. The syntax of the for
loop is as follows:
for initialization; condition; post { // code to be executed }
The initialization
statement is executed before the loop starts, and it usually initializes the loop variable. The condition
expression is evaluated before each iteration of the loop, and if it's true, the loop body is executed. The post
statement is executed at the end of each iteration of the loop, and it usually updates the loop variable.
Here's an example of using a for
loop to iterate over an array in Go:
arr := [5]int{1, 2, 3, 4, 5} for i := 0; i < len(arr); i++ { fmt.Println(arr[i]) }
In this example, the loop variable i
is initialized to 0, and the loop continues as long as i
is less than the length of the array arr
. The loop body prints the value of arr[i]
to the console, and then the post statement i++
increments the value of i
by 1 at the end of each iteration.
Go also provides a more concise syntax for looping over arrays and slices using the range
keyword:
arr := [5]int{1, 2, 3, 4, 5} for i, val := range arr { fmt.Println(i, val) }
In this example, the range
keyword is used to iterate over the elements of the array arr
. The loop variable i
represents the index of the current element, and val
represents the value of the current element. The loop body prints both the index and value of each element to the console.
Finally, Go also supports a for
loop without any initialization, condition, or post statement. This is equivalent to a while
loop in other programming languages:
i := 0 for i < 5 { fmt.Println(i) i++ }
In this example, the loop body is executed as long as the condition i < 5
is true. The loop variable i
is initialized outside of the loop, and it's updated inside the loop using the post statement i++
.