Go by Example: For

for is Go’s only looping construct. Here are three basic types of for loops.

package main
import "fmt"
func main() {

The most basic type, with a single condition.

	i := 1
	for i <= 3 {
		fmt.Println(i)
		i = i + 1
	}

A classic initial/condition/after for loop.

	for j := 7; j <= 9; j++ {
		fmt.Println(j)
	}

for without a condition will loop repeatedly until you break out of the loop or return from the enclosing function.

	for {
		fmt.Println("loop")
		break
	}
}
$ go run for.go
1
2
3
7
8
9
loop

We’ll see some other for forms later when we look at range statements, channels, and other data structures.

Previous example: Constants and iota.

Next example: If/Else.