DEV Community

Cover image for Go while loop
tcs224
tcs224

Posted on

Go while loop

If you programmed in other programming languages before, you may be familiar with a while loop. So you'd think you can use a while loop in Golang. But in Go, things are bit different.

Go doesn't have the while keyword, instead in Go for is Go's "while".
So instead of having something like this:

while sum < 10:
    sum += sum

You have to use for in Go, when you want to use a while loop (this is confusing if you programmed in other languages before):

sum := 1
for sum < 10 {
    sum += sum
}

Of course you need to put in a function (the main function, which is the first function on execution) and write "import fmt", which is a module required for screen output (Println).

package main

import "fmt"

func main() {
    sum := 1
    for sum < 10 {
        sum += sum
    }
    fmt.Println(sum)
}

This outputs the result, as if you used a while loop in another language:

16

Program exited.

Related links:

Top comments (0)