Table of Contents
What is Golang do while
The golang do while provides an implicit loop that iterates over a given block of code as long as the condition remains true. The code within the block will execute at least one time.
The syntax for do while is as follows:
do
while
//blocking) and the loop condition. The code in the block will execute at least one time. The condition following the while keyword must be true to iterate within the loop body. If false, control transfers to statements after do { } while.
A practical example of a golang do while
The code below gives an example of a golang do while looping over an array. In this example, the condition checks if the index of the array is less than 3. If true, it will jump back to the beginning and continue iterating, otherwise it will jump to the end. The code within the block will execute at least one time.
//Creating an array
var myArray = []int{1,3,5,7}
//Looping over the array and checking condition
for index := 0; index < myArray.len(0); index++ {
if myArray.index(index) == 3 {
break //jump back to the beginning of loop } else { //continue iterating } }

How to use Golang do while
In the above program you can see that the program runs till it reaches the break statement. In case you want to test for some condition and then repeat the code till that condition is false, then you can use Go’s do…while statement. The do…while statement executes a block of code at least once. As long as the condition is true at the time, the code block is executed at least once. The program will not halt or break, no matter what.
In your main() function, change the code to do this:
package main
import ( “log” ) // Define scanner type and declare a scanner var parser Scanner = (item *Item) switch item.Type { case “apple”: log.Println(“Picked apple”) case “pear”: log.Println(“Picked pear”) case “orange”: log.Println(“Picked orange”) default: log.Println(“Not picked”) } func main() { // Call the scanner.Parse() routine to get a value from the // user and then run it through our parser p := parser.Parse() }
Try it out:
$ go run 61_do-while.go Not picked Picked orange Picked pear Picked apple $ go run 61_do-while.go orange Picked orange $ go run 61_do-while.go Not picked $
You can see that the scanner will pick the fruits, no matter what. The code block is executed at least once regardless of what you type. It is much easier to use a simple while loop when you have a one time check. In the above case, a simple while loop will work fine:

The benefits of using Golang do while
Using Do-While is better than using If-Else or switch statement. Switch statement should be avoided because it takes control to outside the block. The control is taken randomly, not at the same point. As a result, the switch statement makes program difficult to understand. Excessive use of the switch statement in a program is the primary cause of unmaintainability.
Normally, you need to handle less frequently executed condition first, and more frequently executed condition later. This is an example of reverse order of condition handling. It’s desirable to handle the most frequently executed condition first instead of last. Using do-while is useful for this purpose. The following examples show how to make a reverse-order program using switch and do-while control statements.
The output is not correct. The correct output is as follows:
Code:
package main import ( “fmt” “math/rand” ) var numbers = []float64{ 4.0, 1.2, 3.0, 0i, 2i, -1i } func main(){ // Declare variables and values var a = rand.Intn(5)+1 switch a{ // Try to reverse order of condition handling case 5: fmt.Printf(“%d
“, numbers[“5”]) case 1: fmt.Printf(“%f
“, numbers[“1”]) case 3: fmt.Printf(“%e

Examples of how to use Golang do while
a. The following code example demonstrates using Do-While to increment a number between 1 and 5. The number is incremented as long as the condition True evaluates to true.
// test.go
package main
func main() {
var n int // 1 ————–> 2 ————–> 3 … ————> 5
do { n++ } while (n <= 5) // prints "Hello World" five times if condition is met: true, false, true, false, true }
b. The following code example demonstrates using Do-While to stop program execution by exiting the loop when the condition evaluates to false.
// test.go
package main
import “fmt” // 1 ————–> 2 ————–> 3 … ————> 5 func main() { var n int // Test condition if (!n <= 5) { // stop execution of program fmt.Println("Program has executed all the code. Program is done.") } // increment n = n + 1 }
// Test condition if (!n <= 5) { // stop execution of program fmt.Println("Program has executed all the code. Program is done.") } // increment n = n + 1
Tag wiki markup [ edit ]

Comparison with other programming languages
Golang does have similar syntax to Python’s for loop. If you look at the picture below, you can see that the body of the loop executes once after the condition is false. The if statement at the end of the listing will always be false. The for loop will run the body multiple times.
Listing A: Python Do while loop (https://www.digitalocean.com/community/tutorials/python-do-while-statement)
counter = 0
# The body of the loop is executed once before the condition is checked.
canvas = [] # Create an empty list for i in range( 1, 10 ): # Set a counter to count by 2 canvas.append(i) # Display canvas
print ‘Counter:’, counter
if counter % 2 == 0: # The if statement checks the condition before the loop body. print ‘Break out of the loop.’
counter += 1 # Increment count by 1.
canvas.sort() # Sort its members to display in an ascending order.
print ‘Counter:’, counter
Listing B: Golang Do while loop (https://play.golang.org/p/vOtN0w8ZCK)
counter := 0 // The body of the loop is executed once before the condition is checked.
canvas := [] // Create an empty list
for i := 1 ; i <= 10 ; i++ { // Set a counter to count by 2
canvas = append (canvas, i) // Display canvas
