Monday, November 12, 2018

Learn Golang tutorials - While loop beginner guide with examples

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

Golang while loop 

Like other programming languages, There is no while loop or do while loop in go language. Instead, it provides for loop with a boolean expression. This will executes code of block multiple times until conditional expression is true. if conditional expressions result 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 true of false always. These expressions are created using comparison operators. multiple-expression can also be defined using logical operators. Infinite for loop code block executes infinite times. This conditional boolean expression will never be true. We can write in multiple ways using for expression for without boolean expression. In this case, Condition expression is omitted
func main() {
 number := 1
 for {
  number++
  fmt.Println(number)
 }
}
or other way using for with true boolean values. The boolean expression is always true.
func main() {
 number := 1
 for true {
  number++
  fmt.Println(number)
 }
}
The above programs return the output as follows
1
2
3
...
Infinite times

while loop sleep - wait a time before looping 

while loop alias for loop used to loop the code block. we are going to use sleep function in time package waits for controller before looping code block. time is a builtin package as part of golang. This package provides different functionalities dealing with time-related things. package time inbuilt sleep function 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

 }
}

Related article


EmoticonEmoticon