Golang: loop

By Xah Lee. Date: . Last updated: .

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

for i := 0; i < 4; i++ { }
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.
for x < 3 {}
Test a condition before repeat. (like “while loop”)
for {}
Infinite loop. Break the loop by keyword break, or use keyword continue to exit the inner loop of a nested loop.
for i, x := range array { fmt.Println(i, x) }
Go thru array, slice, map. (called “for range loop”)

Loop a Fixed Number Times

package main

import "fmt"

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

// 0 1 2 3

While Loop

for-loop with just test condition acts like “while loop” in other langs.

package main

import "fmt"

func main() {
	var ss = 1

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

// 1 2 3

Infinite Loop

If no condition is used, loop acts like a infinite loop. You break the loop using keyword break.

package main

import "fmt"

func main() {
	var uu = 1

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

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

// 1 2 3 4

break 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

continue loop

The keyword continue lets you exit the inner loop of a nested 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
			}
		}
	}
}

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

For Range Loop

for i, x := range array { fmt.Println(i, x) }
Loop thru array or slice. [see Golang: Array] [see Golang: Slice]
for _, x := range array { fmt.Println(x) }
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. [see Golang: Map]

Reference

The Go Programming Language Specification - The Go Programming Language#For_statements

The Go Programming Language Specification - The Go Programming Language#Break_statements

The Go Programming Language Specification - The Go Programming Language#Continue_statements

Golang

Examples

Reference