Loops in GoLang
Loops
Loops are one of the iterative constructs used in all programming languages to perform some task iteratively or to recurse over a data structure like a map or an array.
Many languages provide a set of FOR, WHILE and DO WHILE loop but GoLang provides a different approach towards these three loops.
The only looping constructs available in Go is FOR. Let's see how we can achieve different looping scenarios using GO.
Classic For loop
Following is an example of how we can write the classic for loop with initialization, condition and increment step.
For with just condition (While loop)
A while loop kind construct can be achieved using the for loop with just a condition and performing the initialization step before the loop and increment/decrement step inside the loop
Infinite Loop
We can create an infinite loop using a for loop without any condition and using break statement to stop the loop
Iterating an Array
We can iterate over an array using range function
Iterating a Map
We can iterate over a map using the same range function
Next, I will be writing about conditional constructs in Go.
Happy Learning. :D
Comments
Post a Comment