Latest Code Tutorials

Golang For Loop Example | Loops In Golang


Golang for loop statement is used to execute a block of code repeatedly. Go doesn’t have while or do-while loops which are present in other languages like C. Go loop has a three-component. A Go for loop has three components separated by semicolons which are following.

  • The init statement: The init statement executed before the first iteration. This step allows us to declare and initialize any for loop control variables. You are not required to put the statement here, as long as the semicolon appears.
  • The condition expression: This statement is evaluated before every iteration. If a condition is true, the body of the loop is executed. If the condition is false, then the body of the loop does not execute, and the control flow jumps to a next statement just after a for loop.
  • The post statement: This statement executed at the end of every iteration. If the range is available, then the for loop executes for each item in the range.

The for loop in Golang without a condition will repeatedly loop until you break out of the loop or return from the enclosing function. You can also continue to the next iteration of the loop.

Golang for loop example

The syntax for loop in Golang is the following.

for [condition |  ( init; condition; increment ) | Range] {

Let’s see the example.

/* hello.go */

package main

func main() {
   apps := []string{"Facebook", "Instagram", "WhatsApp"}

   for i := 0; i < len(apps); i++ {
	println(i, apps[i])

Okay, so we have defined one slice called apps. Then we have iterated that variable in for loop, and we get the following output.

Go For Loop Example | Golang Loops Tutorial

The for loop will stop iterating once the boolean condition evaluates to false.

Unlike the other languages like C, C++, Java, or JavaScript, no parentheses are required to surround the three components of a for statement, but the braces { } are always required.

We can also use the range function with for loop. Let’s see the following example.

/* hello */

package main

import "fmt"

func main() {
   apps := []string{"Facebook", "Instagram", "WhatsApp"}

   for i, app := range apps {
	 fmt.Println(i, app)

The output of the above code is the same.

Go For Loop Example

We have used the range keyword when we need to iterate each element of the slice in Go.

Finally, Golang for loop example tutorial is over.

Recommended Posts

Golang Constants Example

Golang Maps Example

Golang Arrays Example

Golang Structs Example

Golang Receiver Function Example

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.