While Loops in Go

While loops are common in pretty much every language, and despite missing the keyword while, they are still possible! If you just want to know how to write one, the short answer is to write for instead of while. Like this:

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	finished := false

	for !finished {
		num := rand.Intn(5)

		fmt.Println(num)

		if num == 3 {
			finished = true
		}
	}
}

Try it out here.

I’m not sure of the exact rationale behind it, but my guess is that for loops usually have the following structure:

for initialise; condition; increment/update {
	...
}

Both the initialise and increment/update are optional, and if you choose to leave them out then there is no real need to include the semi-colons. So this allows you to write a loop like above:

for condition {
	...
}

Now, Go being the pragmatic language that it is, doesn’t duplicate this structure. Why add a new keyword when it doesn’t actually add anything to the language?

Leave a Reply

Your email address will not be published. Required fields are marked *