Gaaker Go

Golang For loop

The for loop is the only loop structure in Go.

The basic for loop is composed of three parts, which are separated by ;

init statement
Execute before the first iteration and only once. Usually a short variable declaration.
condition expression
Execute before each iteration. If the condition is false, it exits the iteration, otherwise the loop continues to iterate.
modification statement
Execute after each iteration. Usually update counter.
for init; condition; modification {
    ...
}

The following is a complete code example.

package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        fmt.Printf("This is the %d iteration\n", i)
    }
}

Below is the program output:

This is the 0 iteration
This is the 1 iteration
This is the 2 iteration
This is the 3 iteration
This is the 4 iteration
< For loop For loop >