Go - for Loop Example

In this example, we will show you how to use for loop in Go with an example.

The for loop is Go’s only looping construct.

Go - for Loop Example

Here are some basic types of for loops:


package main

import "fmt"

func main() {

    // The most basic type, with a single condition.
    i := 1
    for i <= 4 {
        fmt.Println(i)
        i = i + 1
    }

     // A classic initial/condition/after for loop.
    for j := 5; j <= 7; j++ {
        fmt.Println(j)
    }

    // for without a condition will loop repeatedly until 
    // you break out of the loop or return from the enclosing function.
    for {
        fmt.Println("loop")
        break
    }

    // You can also continue to the next iteration of the loop.
    for n := 0; n <= 5; n++ {
        if n%2 == 0 {
            continue
        }
        fmt.Println(n)
    }
}

Output:

1
2
3
4
5
6
7
loop
1
3
5

Comments