Golang - For loop
Three-component loop
sum := 0
for i := 1; i < 5; i++ {
sum += i
}
fmt.Println(sum) // 10 (1+2+3+4)
This version of the Go for loop works just as in C/Java/JavaScript.
- The init statement,
i := 0
, runs. - The condition,
i < 5
, is evaluated.- If it’s true, the loop body executes,
- otherwise the loop terminates.
- The post statement,
i++
, executes. - Back to step 2.
The scope of
i
is limited to the loop.While loop
If the init and post statements are omitted, the Go
for
loop behaves like a C/Java/JavaScript while loop:power := 1
for power < 5 {
power *= 2
}
fmt.Println(power) // 8 (1*2*2*2)
- The condition,
i < 5
, is evaluated.- If it’s true, the loop body executes,
- otherwise the loop terminates.
- Back to step 1.
Infinite loop
By also leaving out the condition, you get an infinite loop.
sum := 0
for {
sum++ // repeated forever
}
fmt.Println(sum) // unreachable
For each loop
Looping over elements in slices, arrays, maps, channels and strings is often better done using the
range
keyword:strings := []string{"hello", "world"}
for i, s := range strings {
fmt.Println(i, s)
}
0 hello
1 world
For more examples, see Range loops (for each loops) explained.
Exit a loop
The
break
and continue
keywords work just as they do in C/Java/JavaScript.sum := 0
for i := 1; i < 5; i++ {
if i%2 != 0 { // skip odd numbers
continue
}
sum += i
}
fmt.Println(sum) // 6 (2+4)
- A
continue
statement begins the next iteration of the innermostfor
loop at its post statement. - A
break
statement terminates execution of the innermostfor
,switch
, orselect
statement.