Essential Go  Edit on GitHub      File Issue

for, while loops

Go has only one looping construct: for loop.

Here are basic forms.

Full form

for i1 := 0; i1 < 5; i1 += 2 {
	fmt.Printf("i1: %d\n", i1)
}
i1: 0
i1: 2
i1: 4

Every loop statement is optional.

Without initialization statement

i2 := 0
for ; i2 < 5; i2 += 2 {
	fmt.Printf("i2: %d\n", i2)
}
i2: 0
i2: 2
i2: 4

Without test expression

Using break to terminate the loop

i3 := 0
for ; ; i3 += 2 {
	fmt.Printf("i3: %d\n", i3)
	if i3 >= 5 {
		break
	}
}
i3: 0
i3: 2
i3: 4
i3: 6

Without increment statement

for i4 := 0; i4 < 5; {
	fmt.Printf("i4: %d\n", i4)
	i4 += 2
}
i4: 0
i4: 2
i4: 4

Infinite loop

i5 := 0
for {
	fmt.Printf("i5: %d\n", i5)
	i5 += 2
	if i5 >= 5 {
		break
	}
}
i5: 0
i5: 2
i5: 4

for loop with range

a := []int{1, 3, 5}
for idx, value := range a {
	fmt.Printf("idx: %d, value: %d\n", idx, value)
}
idx: 0, value: 1
idx: 1, value: 3
idx: 2, value: 5
  ↑ ↓ to navigate     ↵ to select     Esc to close