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.
    • If it’s true, the loop body executes,
    • otherwise the loop terminates.
  3. The post statement, i++, executes.
  4. 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.
    • If it’s true, the loop body executes,
    • otherwise the loop terminates.
  2. 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 innermost for loop at its post statement.
  • A break statement terminates execution of the innermost for, switch, or select statement.

Comments