Essential Go  Suggest an edit

for, while loops

Go has only one looping construct: for loop.

Here are basic forms.

Full form

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

Every part of loop statement is optional.

Without initialization statement

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

Without test expression

Using break to terminate the loop

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

Without increment statement

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

Infinite loop

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

for loop over a slice 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