GoGoPrimer
< Back to module

Control flow

for, the only loop

Unlike most languages, Go has neither `while` nor `do-while`: everything is done with `for`. The form closest to a classic C-style `for` looks like this.

for i := 0; i < 5; i++ {
fmt.Println(i)
}
// affiche 0, 1, 2, 3, 4

By omitting the initialization and the increment, only a condition remains: this is the equivalent of a `while`.

count := 0
for count < 3 {
fmt.Println(count)
count++
}

With no condition at all, `for` loops forever; you exit it with `break`. And to iterate over a collection (slice, array, map, string), you use `for ... range`, which returns the index and the value at each iteration.

fruits := []string{"pomme", "poire", "kiwi"}
 
for index, fruit := range fruits {
fmt.Println(index, fruit)
}
// 0 pomme
// 1 poire
// 2 kiwi
 
for {
fmt.Println("boucle infinie")
break // indispensable pour ne pas boucler éternellement
}

If you only need the value, not the index, replace it with `_`: `for _, fruit := range fruits`. A declared-but-unread variable is a compile error, even inside a loop.

Your turn

Write a `sum(numbers []int) int` function that adds up every element of an integer slice with a `for range`.

func sum(numbers []int) int {
// à compléter
}