In the Go programming language, you can use the for
loop to execute a block of code multiple times. There are several ways to use the for
loop in Go.
Here are some examples of using the for
loop in Go:
for i := 0; i < 10; i++ { fmt.Println(i) }
This loop will print the numbers 0 through 9. The initialization, condition, and increment statements are separated by semicolons.
i := 0 for i < 10 { fmt.Println(i) i++ }
This loop is equivalent to the traditional for loop above. It will print the numbers 0 through 9.
for { fmt.Println("Infinite loop") }
This loop will run indefinitely. It is equivalent to a while(true)
loop in other languages.
numbers := []int{1, 2, 3, 4, 5} for i, number := range numbers { fmt.Println(i, number) }
This loop will iterate over the elements in the numbers
slice and print the index and value of each element.