Golang: loop

By Xah Lee. Date: . Last updated: .

Go has only one loop construct, the for-loop.

For-Statement

for i := 0; i < 4; i++ { body }
Loop a fixed number times with a incremental variable.

Scope of i is the whole for statement.

Note: no parenthesis after the for keyword. Adding parenthesis creates invalid syntax. Curly brackets {} are always required.

package main

import "fmt"

func main() {
	for i := 0; i < 4; i++ {
		fmt.Printf("%v ", i)
	}
}

// 0 1 2 3
for test {body}
Test a condition before repeat. (like “while-loop”)
package main

import "fmt"

func main() {
	var xx = 1

	// for-loop with just test condition
	// this acts like “while loop” in other langs
	for xx <= 3 {
		fmt.Printf("%v ", xx)
		xx++
	}
}

// 1 2 3
for {body}
Infinite loop. Break the loop by keyword break, or use keyword continue to skip rest of the inner loop.
package main

import "fmt"

func main() {
	var xx = 1

	// infinite loop
	for {
		fmt.Printf("%v ", xx)
		xx++

		// use break to exit
		if xx > 4 {
			break
		}
	}
}

// 1 2 3 4

For Range Loop (Iterate Array, Slice, Map)

for i, x := range array { fmt.Println(i, x) }
Go thru Array or Slice .

If one of the variable you don't need, name it _, else compiler will complain. The _ is called Blank Identifier.

for key, value := range map { fmt.Println(key, val) }
Go thru Map.

break (Exit Loop)

The keyword break lets you break a loop. Useful when you want to exit the loop when some condition is met.

package main

import "fmt"

func main() {

	for i := 0; i < 9; i++ {
		fmt.Printf("%v ", i)
		if i == 4 {
			break
		}
	}
}

// 0 1 2 3 4

keyword continue (Exit Current Inner Loop)

The keyword continue skips the rest statements of the inner loop and continue at the beginning of the inner loop.

package main

import "fmt"

func main() {
	for i := 1; i <= 3; i++ {
		for j := 1; j <= 99; j++ {
			if j <= 2 {
				fmt.Println(i, j)
			} else {
				continue
				fmt.Printf("%v\n", "this never reached")
			}
		}
	}
}

// 1 1
// 1 2
// 2 1
// 2 2
// 3 1
// 3 2