While Loop in Golang

Learn via video courses
Topics Covered

Overview

In generic programming, the while loop is a crucial component. However, there is no dedicated keyword for a while loop in Golang. There are only for-loops. The for-loop in Go can be used as a while loop. In this article, we will see how to use a while loop in Golang.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Why do we Use the "while" Loop in Golang?

While loops are a fundamental iterating mechanism in Go and are typically used when we are unsure how many iterations are required. When utilizing a while loop, it is critical to provide a condition that stops the loop; else, the loop would run continuously.

The while loop is useful in several situations, such as:

  • Iterating over a collection of items, like an array or a slice, and acting on each item.
  • Continuously polling a resource, like a file or a network connection, until a certain condition is met.
  • Running a background process, like a server or a background task, that should continue running until the program is terminated.

The while loop can also be used in combination with other control flow statements like a break or continue to control the flow of the iteration.

Parts of the "while" Loop Structure in Golang

The unique thing about for loop is that they are divided into three individual parts, which are optional in Golang; this feature helps to work for loop as a while loop as well.

We need only the for keyword to create the while loop by skipping other optional parts of the for loop.

Free Courses by top Scaler instructors
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course

Init Statement

The initialization statement in Go executes only once, and it's optional. This statement is performed before the first iteration begins. (An iteration occurs each time the for statement performs the statements contained within it.) It is as simple as defining or declaring a variable.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

Condition Expression

The condition statement contains a boolean expression that is evaluated at the start of each loop iteration. If the conditional expression returns true, the loop is executed.

Post Statement

The post statement is executed after each successful iteration, and any conditions that are met are rechecked. If the condition is true it will continue the loop to recheck, and if it is false it will simply be terminated then and there only.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Syntax

The while loop here evaluates the condition. If the condition is as follows:

  • true: statements within the loop are run, and the condition is re-evaluated
  • false: the loop is terminated.

Alternative way:

Example

So, here are some examples of how to accomplish that.

Output for the above code:

Run the code!

Explanation of the code:

In the above code, we first initialize the variable c for starting the loop count with 0, then the next line defines the while loop which will run till c < 5 and prints the count until the loop condition will fall under true condition else terminates, for incrementing the count we have c++ which is increasing the count every time till c < 5.

Note:
The while loop will never terminate if we don't include c++ and fall into an infinite loop.

Some more examples using while loop:

Loop through string characters using while loop:

Output:

Run the code!

Explanation of the code:

  • In the above code, we define the variable message which stores theHello World! string, and a count variable which helps to track the count of the indexes of the message variable.
  • Using fmt. println we are printing the indexes along with the characters one by one.
  • And finally, increment the count variable, or else it will iterate forever.

Conclusion

  • In Golang, we use the "for" loop as a "while" loop. The key to understanding this concept is to have a clear understanding of the three parts of the for loop and how they can be used. The "for" loop allows us to accomplish the same thing as a "while" loop, with the added flexibility of being able to perform an action before each iteration, perform the action, and then perform an action after each iteration.
  • It is important to remember that while loops can fall into an infinite loop if the condition is not met, which will cause the program to crash. Always make sure that the while loop will eventually exit.