Golang for loop

Syntax of the for loop in Golang:

for initialization; condition; update {
  statement(s)
}
  1. The initialization initializes and/or declares variables and is executed only once.
  2. Then, the condition is evaluated. If the condition is true, the body of the for loop is executed, otherwise the loop is done
  3. The update updates the value of initialization.
  4. Back to step 2.
Example:
sum := 0
for i := 1; i < 5; i++ { // The scope of i is limited to the loop.
    sum += i
}
fmt.Println(sum) // 10 (1+2+3+4)
  1. The init statement, i := 1, runs.
  2. The condition, i < 5, is computed. If true, the loop body runs, otherwise the loop is done.
  3. The post statement, i++, runs.
  4. Back to step 2.