Unlike many other languages, Go does not have while loops; instead, for loops can be used to replace while loops by using the following syntax.
Syntax
123
forcondition{//Do stuff each iteration}
- while (condition) => for condition with no parentheses around condition
Example:
12345
accumulator:=0foraccumulator<10{accumulator+=1}// Output = "Accumulator at end of while for-loop: 10"
Infinite Loops
Even though there are no while loops in Go, a developer can write infinite loops by using a for loop with no condition, like the following:
Syntax
123
for{// Code that runs on each iteration goes here...}
Example: Reads user input in terminal, forever
12345678
//Imports "bufio" and "os" packages to parse and read user input in terminalreader:=bufio.NewReader(os.Stdin)fmt.Printf("Testing Infinite Looping... \n")fmt.Printf("-------------\n")for{text,_:=reader.ReadString('\n')fmt.Printf("Text entered: %s\n",text)}