Golang tutorials -Learn While Loop example

This blog post covers learn while and do while loop guide with examples in Golang.

Golang do while loop example

Like other programming languages, there is no while loop or do while loop syntax in the go language.

Instead, it provides for a loop with a Boolean expression. These can be used in place of the do-while loop in the Go language.

It executes the block of code multiple times until the conditional expression is true. if conditional expressions result in false, It exits the control from the loop block.

Each iteration is executed once the condition is true. Conditional expressions are evaluated and executed before each iteration.

Here is the syntax for the while loop alias for loop with a Boolean expression

for boolean-expression {
// code block
}

boolean-expression results in true of false always.

These expressions are created using comparison operators.

multiple-expression can also be defined using logical operators.

Infinite for loop can execute code block infinite times and the conditional boolean expression will never be true.

We can write in multiple ways using for expression without boolean expression. In this case, the Condition expression is omitted.

package main

import (
    "fmt"
    "time"
)
func main() {
    number: = 1
    for {
        number++
        fmt.Println(number)
    }
}

or another way using for with boolean value-true. The boolean expression is always true.

package main

import (
    "fmt"
    "time"
)
func main() {
    number: = 1
    for true {
        number++
        fmt.Println(number)
    }
}

The above programs return the output as follows.

1
2
3
...
Infinite times

Golang while loop example

while loop alias for loop is used to loop the code block.

Use the sleep function in the time package to wait for the controller before looping the code block.

We have added a sleep code to sleep for 300 milliseconds before going to the next iteration. time is a built-in package as part of golang. This package provides different functionalities dealing with time-related things.

time package has an inbuilt sleep function that waits 300 milliseconds for each iteration during an infinite loop.

package main

import (
    "fmt"
    "time"
)

func main() {
    number: = 1
    for true {
        number++
        fmt.Println(number)
        time.Sleep(300 * time.Millisecond) // control stops here and sleeps for 300 milli seconds

    }
}

Conclusion

To summarize, there is no do-while or while loop syntax in Golang, Instead, you can choose for loop and learn the examples.