golang can repeat a code block with a while loop. The while loop repeats code until a condition is true.

While loops are used when you are not sure how long code should be repeated. Think of a tv that should continue its function until a user presses the off button.

While loops in golang

Example

The program below is an example of a while loop in golang. It will repeat until a condition is true, which could be forever.

The code block can contain anything, from statements to function calls.


package main

import "fmt"

func main() {
     i := 1
     max := 20

     // technically go doesnt have while, but
     // for can be used while in go.
     for i < max {
         fmt.Println(i)
     i += 1
     }
}
            

In the example it repeats the code block until variable i is greater than max. You must always increment the iterator (i), otherwise the while loop repeats forever.

The code block can be as many lines as you want, in this example its just one line of code that gets repeated.

Exercises

  1. How does a while loop differ from a for loop?

Download Answers