Go Language for Loop Examples

‮th‬tps://www.lautturi.com
Go Language for Loop Examples

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:

  1. Traditional for loop:
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.

  1. While loop:
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.

  1. Infinite loop:
for {
    fmt.Println("Infinite loop")
}

This loop will run indefinitely. It is equivalent to a while(true) loop in other languages.

  1. Range loop:
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.

Created Time:2017-10-28 20:40:39  Author:lautturi