AppDividend
Latest Code Tutorials

Go For Loop Example | Golang Loops Tutorial

0

Go For Loop Example | Golang Loops Tutorial is today’s topic. Go has only one looping construct which is the for loop. The 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 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.

Go For Loop Example

The syntax of for loop in Go is following.

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

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.

Leave A Reply

Your email address will not be published.

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