ado.xyz
Blog Courses About

How to Create a While Loop in Go

April 30, 2020

Loops are one of the most fundamental control flow elements of any programming language. Most programming languages support many types of loops such as the for, while, and for-each loops. The Go programming language only has one type of loop, and that is the for loop.

The for loop in Go is special. It allows you to essentially emulate any sort of loop, including the while loop. You do this by changing the type of parameters you supply to it.

While Loop in Go

The syntax for a traditional for loop in most programming languages, including Go, is as follows:

for i := 0; i < 10; i++ {
  // Print the value of i
  fmt.Println(i)
}

The three arguments supplied to the for loop are:

  • The initializer, which is evaluated when the loop starts
  • The test condition we’re checking against, so while this remains true, the loop will run
  • Finally, the updater, which tells us what to do once one iteration of the loop has run

To create a while loop in Go, you simply omit the initializer and the updater and just leave the test condition. So to create a while loop in Go, you would do:

i := 0

for i < 10 {
  fmt.Println(i)
  i++
}

In the above example, while we did omit the initializer and updater from the arguments passed into the loop, we still had a variable outside of the loop hold our counter and incremented it in the loop logic itself. But let’s say our use case was different and we wanted the loop to run until a certain condition was met.

Infinite While Loop in Go

In the next example, we’ll create an infinite loop that will be terminated upon a specific condition being met, that’s not necessarily based on an increment or decrement expression. We’ll generate a random number between 1 and 100, and we’ll exit the loop once the random number equals 7.

var random int

for {
  random = rand.Intn(100)

  fmt.Println(random)

  if random == 7 {
    fmt.Println("Our Random Number is 7")
    break
  }

}

Our for loop will run endlessly until the random variable is assigned the value of 7, at which point our condition will be met, our program will print out the message "Our Random Number is 7", and finally break out of the loop.

While the Go programming language may only have the for loop, it is very flexible and allows us to implement many different types of loops by simply modifying the arguments we pass into it.

Newsletter

Subscribe to the newsletter and be the first to know when I publish new content. No Spam.