How to program a while loop in golang?

How to program a while loop in golang?

Golang syntax does not have a keyword for while loop but we can use the for loop syntax to create a while loop in Go.

How to program a while loop in Golang?

Technically, Golang syntax does not have a keyword for while loop but we can use the for loop syntax to create a while loop in Go.

While loop syntax (using For)

We can emulate the working of a while loop using for loop in Go. The first initialization part and the increment part of the for loop can be ignored and then it becomes a typical while loop which can be found in other languages.

for condition {
	// code block
}

Golang checks for the condition and then takes one of the two branches based on the result of the condition

  1. If the condition is true, execute the code block. After execution of the code block, it goes back to check the same condition
  2. If the condition is false exits the for loop and moves to the next statement.

Flowchart.png

Note: When using the for as while loop, we should be careful to not cause an infinite loop. The condition needs to become false at some point inside the Code Block

canStop = true // Initialize the variable to use in condition
for canStop {
    // code block
    // all your logic goes here

    // Condition for termination of the loop (Imp)
    if result > 400 {
        canStop = false
    } 
}

Most of cases, you would want the while loop to be terminated at some point and so the termination condition becomes important.

Why use while loop syntax

While loop is mostly used when the number of iterations of the loop is not clear and it depends on the condition.

Let’s look at an example

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	maxLimit := 30

	counter := 0
	for counter < maxLimit {
		fmt.Println("Current Counter Value - ", counter)
		counter += rand.Intn(10) // Generates a random number and increments the counter
	}
}

There are the same patterns you can see in this example as well. We have counter variable which is initialized to 0.

  1. The condition is checked 0 < 30 which will be true and so goes into the loop
  2. We are printing the current counter value
  3. We are incrementing the counter variable with a random number generated between 0 and 10. This is the reason you will not be able to predict the number of iterations at the start. Each time the program runs, you might have a different number of iterations in the for loop.

So it is better to use the while syntax in this case as it makes more sense.

Output

Current Counter Value -  0
Current Counter Value -  6
Current Counter Value -  11
Current Counter Value -  18
Current Counter Value -  23
Current Counter Value -  29

When not to use the while loop syntax

When you are dealing with a set number of iterations, for loop with regular syntax is more convenient.

package main

import "fmt"

func main() {
	fruits := []string{"Apple", "Orange", "Pineapple", "Grapes", "Watermelon"}

	// Using while loop like syntax
	index := 0
	for index < len(fruits) {
		fmt.Println(fruits[index])
		index++
	}

	// Using the for loop with init and update statement
	for i := 0; i < len(fruits); i++ {
		fmt.Println(fruits[i])
	}
}

In this example, we have a comparison between the two syntax formats and you can see which is easy to understand and requires less code to write.

Output

Apple
Orange
Pineapple
Grapes
Watermelon
Apple
Orange
Pineapple
Grapes
Watermelon

Do while loop in Golang

You can also do something similar to Do.. while loop in golang using the below syntax


result := 0
for { // Runs infinitely
	result++

	// Breaking condition
	if result > 400 {
		break;
	}
}
  1. There is no condition to check in the for loop and so it runs infinitely
  2. We have a check inside the loop to see if we can break the loop and if that condition is met, then we use the break keyword to break out of the loop.

Common Mistakes to Avoid When Using While Loops in Golang

Let’s explore Go loops and understand some common errors

  • Forgetting the Loop Condition: This is the equivalent of programming an endless marathon. Without a condition to check, your program will keep looping until the cows come home, or worse, until it crashes.

  • Improper Initialization: Before your loop takes its first step, it needs a starting point. Failing to properly initialize your loop variable can lead to unpredictable results or runtime errors.

  • Incorrect Increment: Like a hiker picking the wrong path, an incorrect increment can send your loop off course. It could either end prematurely or keep going without ever reaching the destination.

Let’s visualize these mistakes in a tabular form:

MistakeDescriptionConsequence
Forgetting the Loop ConditionNo condition to checkEndless loop or crash
Improper InitializationNo starting pointUnpredictable results or runtime errors
Incorrect IncrementWrong step-size or directionEnd too soon or endless loop

Key Differences Between While and For Loops in Golang

In the playground of Golang, the classic ‘while’ loop is notably absent, making ‘for’ loops the go-to method for cycle repetition. The ‘for’ loop is more than capable of donning the ‘while’ loop’s hat. Let’s dive into the key differences and how we can use ‘for’ loop as a ‘while’ loop.

Summary

Loop TypeStructureUse Case
For LoopInitializes a variable; sets a condition; increments/decrements variableWhen you know the exact number of iterations
While Loop (as For Loop)Sets a condition onlyWhen the number of iterations is uncertain or depends on a condition

For loop in golang

For the complete reference, you can look at the for loop syntax mentioned below.

for initialize; condition; after_loop {

}

There are three parts to the for loop

  • initialize - Runs only once at the start of the loop
  • condition - Check every time before each iteration
  • after_loop - Statement runs after each iteration is complete

If you want to learn more about the for loop, you can check this article where we talk in detail about the for loop - https://eternaldev.com/blog/go-learning-for-loop-statement-in-depth/