BeginnerLesson 4 of 15
Loops: for only – Go
Go has exactly one loop construct – with many forms.
Go has only for. It comes in three forms: classic with a counter, as a "while" with just a condition, and as an infinite loop. Since Go 1.22, for i := range 3 conveniently counts from 0 to 2.
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println("Runde", i)
}
n := 0
for n < 3 { // like while
n++
}
fmt.Println(n) // 3
for i := range 3 { // Go 1.22+
fmt.Print(i, " ")
}
fmt.Println() // 0 1 2
}With range you iterate over slices, arrays, strings, maps and channels. You get the index and value (or key and value). You discard values you do not need with _.
package main
import "fmt"
func main() {
fruechte := []string{"Apple", "Pear", "Cherry"}
for i, f := range fruechte {
fmt.Println(i, f)
}
for _, f := range fruechte {
fmt.Print(f[:1], " ") // first letter
}
fmt.Println()
for i, r := range "Gö" { // over runes, not bytes
fmt.Println(i, string(r))
}
}break ends the loop, continue jumps to the next iteration:
package main
import "fmt"
func main() {
n := 0
for {
n++
if n%2 == 0 {
continue
}
if n > 7 {
break
}
fmt.Print(n, " ") // 1 3 5 7
}
fmt.Println()
}WarningBefore Go 1.22, all iterations shared the same loop variable – goroutines or closures then often saw only the last value. Since 1.22 (with
go 1.22 or newer in go.mod), every iteration has its own copy. With maps, the order of range is deliberately random.