for loops, break and continue
- Version
- 1.27
- Review
- Draft
Summary#
for is Go's loop statement. It covers counted loops, condition-only loops, endless loops and range loops. A label lets break or continue act on an outer loop.
Syntax#
for i := 0; i < n; i++ {}
for condition {}
for {}
for i := range n {}
Example#
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
fmt.Println("counted", i)
}
size := 100
for size > 10 { // condition only
size /= 3
}
fmt.Println("size", size)
for i := range 2 { // 0 and 1
fmt.Println("range", i)
}
grid := [][]int{{1, -2, 3}, {4, 5, 0}, {7, 8, 9}}
sum := 0
rows:
for _, row := range grid {
for _, cell := range row {
if cell == 0 {
break rows // leaves both loops
}
if cell < 0 {
continue
}
sum += cell
}
}
fmt.Println("sum", sum)
}
Expected output#
counted 1
counted 2
counted 3
size 3
range 0
range 1
sum 13
Common mistakes#
In for _, item := range items, item is a copy of the element. Assigning to it leaves the slice unchanged. Use the index, as in items[i] = value, to update elements.
Version applicability#
Ranging over an integer requires Go 1.22 or later. Use a three-part loop on earlier versions. The other forms shown also apply to earlier versions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0