Go: For loops explained

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.

  1. The init statement, i := 0, runs.
  2. The condition, i < 5, is evaluated.
  3. If it's true, the loop body executes,
  4. otherwise the loop terminates.
  5. The post statement, i++, executes.
  6. 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)
  1. The condition, i < 5, is evaluated.
  2. If it's true, the loop body executes,
  3. otherwise the loop terminates.
  4. 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)

Comments

Be the first to comment!