Golang for loop
Syntax of the for loop in Golang:
for initialization; condition; update {
statement(s)
}
- The initialization initializes and/or declares variables and is executed only once.
- Then, the condition is evaluated. If the condition is true, the body of the for loop is executed, otherwise the loop is done
- The update updates the value of initialization.
- 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)
- The init statement, i := 1, runs.
- The condition, i < 5, is computed. If true, the loop body runs, otherwise the loop is done.
- The post statement, i++, runs.
- Back to step 2.