GoLang

Explain Loops in Go Language | Go Programming Tutorial

Explain Loops in Go Language | Go Programming Tutorial

Explain Loops in Go Language | Go Programming Tutorial

In this article, you will learn:

  • What are Loops in Go Programming?
  • Types of Loops in Go Programming Language

What are Loops in Go Programming?

Go Language has only a single loop i.e for-loop. A for loop contains a repetition control structure that executes a set of lines again and again. There are so many different loops in the Go Programming Language. 

Types of Loops in Go Programming Language

1. Simple for loop: It works similarly as it works in other languages such as C, C++, Java, C#, etc.

SYNTAX: 

for initialization; condition; increment/decrement { 

       // set of statements

}

Points to be Noted:

Initialization: It is optional and executes before the loop starts. It initializes the value of the variable.

Condition: It evaluates the conditions. If it returns true, it executes the set of statements inside the loop. 

Increment/Decrement: It increments or decrements the value, then again control goes to the condition statement. It verifies the condition if it is true. It executes the set of statements. 

2. For loop as infinite Loop: It can also be used as an infinite loop by removing all the statements from the loop. When the user did not write any conditions, then it means the condition is true. So, the loop goes on.

SYNTAX:

for{

   // set of statements

}

3. For loop as a while Loop: It can also work as a while loop. The loop will execute till the given condition is true. When the condition is false the loop ends.

SYNTAX: 

for condition{

   // set of statement

}

4. Simple range in for loop: The range is used in the for loop as well. 

SYNTAX:

for I, j:= range variable{

  // set of statements

}

5. Using for loop for strings: A for loop can iterate over the Unicode code point for a string

SYNTAX:

for index, char:=range str {

  //set of statement

}

6. For Maps: It can iterate over the key and value pairs of the map.

SYNTAX:

for key value:= range map {

   // set of statement

}

Yamini  Sharma

I am working as a professional engineer in "HIghRadius Technologies Pvt. Ltd." Passionate about learning and exploring new technologies. Enthusiast in writing and sharing what I have in my knowledge bucket.