Loops with for
| Classic three-part for | |
| for as while | |
| Range over slices and maps | |
| break and continue |
Classic three-part for
Go has a single loop keyword: for. The classic form has three parts separated by semicolons: the setup, the condition checked before every step, and the update that runs after every step.
package main
import "fmt"
func main() {
sum := 0
for i := 1; i <= 5; i++ {
sum += i
}
fmt.Println(sum)
}
go run main.go
15
The counter variable declared in the setup lives only inside the loop. Opening braces stay on the same line as the for header, exactly like if and switch.
for as while
Drop the three parts and for behaves like a while loop from other languages: it repeats while its single condition holds. This form fits readers, retries, and countdowns where no counter is needed.
package main
import "fmt"
func main() {
n := 3
for n > 0 {
fmt.Println(n)
n--
}
}
3
2
1
A bare for with no condition at all loops forever, so pair it with a break or a return that always becomes reachable.
Range over slices and maps
Range walks a slice or a map and hands you each element in turn. Over a slice you receive the index and a copy of the element; over a map you receive the key and the value.
package main
import "fmt"
func main() {
nums := []int{1, 2, 3}
for i, n := range nums {
fmt.Println(i, n)
}
ages := map[string]int{"Ada": 36, "Bob": 28}
for name, age := range ages {
fmt.Println(name, age)
}
}
Map iteration order changes from run to run on purpose, so never rely on it. When order matters, collect the keys into a slice and sort that slice first.
break and continue
Break exits the loop at once, while continue skips the rest of the current step and jumps to the next one. Together they keep loop bodies flat by handling special cases first.
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
if i%2 == 0 {
continue
}
if i > 7 {
break
}
fmt.Println(i)
}
}
1
3
5
7
Here continue skips even numbers and break stops the loop once values grow past 7. Reading such loops from top to bottom shows each filter before the useful work at the end.
Next: Arrays
Article author: Arthur Isaev