Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
In Development Last updated: April 19, 2023
Share on:
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Learn all about Golang for loops by coding several useful examples.

Recently programming languages such as Rust, Golang, and TypeScript have become super popular among developers. If you’re interested in back-end development and DevOps, you should consider learning Golang is an excellent option!

If you are a beginner picking up the fundamentals of a programming language, loop constructs are one of the first concepts you should understand.

Golang provides only the for loop construct. And we’ll learn about for loops and also how to emulate other loops using the for loop.

Let’s begin!

Syntax of Golang For Loop

In Golang, you can create for loop using the following syntax:

for initialization; condition; update {
    // do something
}

Here, 

  • initialization denotes the initialization of the looping variable.
  • condition is the looping condition that determines the execution of the loop body. So long as the looping condition evaluates to true, the statements in the loop body get executed. And when the condition becomes false, the control exits the loop.
  • update denotes the update to the looping variable—usually an increment or a decrement.

💡 Notice how this is similar to the C for loop only without the parentheses.

Here’s the control flow in Golang for loops:

Syntax-of-Golang-For-Loop

Time to code some examples!⏰ To code along, you can either use a local installation of Golang or run the examples on Go Playground.

Golang For Loop Examples

Let’s use the syntax we’ve just learned to write our first for loop. Here is a simple for loop that prints out the numbers 1 up to 5 in steps of one.

package main

import "fmt"

func main() {
	fmt.Println("For loop:")
	num := 5
	for i := 1; i <= num; i++ {
		fmt.Println(i)
	}
}

We initialize the looping variable i to 1, set the condition to i <= 5, and increment the looping variable by one after every iteration. And here’s the output:

//Output
For loop:
1
2
3
4
5

Let’s write another for loop. This loop starts from 5 and counts down to 1; it goes on till the looping variable is greater than or equal to 1. So we decrement the looping variable by one after each iteration.

package main

import "fmt"

func main() {
	fmt.Println("For loop:")
	num := 5
	for i := num; i >= 1; i-- {
		fmt.Println(i)
	}
}

And we get the expected output:

//Output
For loop:
5
4
3
2
1

What is the Scope of the Looping Variable?

The scope of the looping variable is limited to the for loop block, and is not accessible outside the loop.

To verify this, let’s try accessing the value of the looping variable i outside the loop:

package main

import "fmt"

func main() {
	fmt.Println("For loop:")
	num := 5
	for i := 1; i <= num; i++ {
		fmt.Println(i)
	}
	fmt.Println(i)

}

As expected, we run into an error that states i is an undefined (and its scope is restricetd to the for loop):

// Output
./prog.go:11:14: undefined: i

Infinite For Loop in Golang

Infinite-For-Loop-in-Golang

Can we have infinite for loops in Go? Yes, we sure can! 

If you look at the control flow of for loop:

  • The loop body will continue to execute so long as the condition evaluates to true.
  • When the condition becomes false, the control exits the loop.
  • So if the condition never becomes false (or is always true), we have an infinite loop.

But you can also use the for loop without the initialization, condition, and update—without running into syntax errors. So if you can make the loop run infinitely even using a for loop construct like this:

package main

import "fmt"

func main() {
	for {
	   fmt.Println("running...")
	}
}
//Output
running...
running...
running...
running...
running...
//and it goes on forever!

In this example, we set the variable num to 5. And the looping condition is num >= 5. So the loop runs so long as num is greater than or equal to zero.

package main

import "fmt"

func main() {
	num := 5
	for num > 0 {
		fmt.Println(num)
	}
}

Because the value of num never changes, the condition always evaluates to true, and the loop runs forever!

//Output
5
5
5
5
5
5
//and it goes on forever!

All Golang has only the for loop construct, we can try to emulate the while and do-while loops using for loops. So let’s learn how to do it!

Emulating While Loop using For Loop

The while loop generally takes the following form:

// initialize looping var
while (condition){
    // do something
    // update looping var
} 

If you recall, in the first infinite for loop we wrote: we used the following for loop—without the initialization, condition, and update.

for {
// the simplest infinite loop
}

So we can modify the for loop to contain only the condition (in the following form) to emulate the while loop:

//initialize looping var
for condition {
 // do something
 // update looping var
}

Here’s the while loop equivalent of the first for loop that we wrote:

package main

import "fmt"

func main() {
	fmt.Println("Emulating while loop")
	num := 5
	for num > 0 {
		fmt.Println(num)
		num--
	}
}
//Output
Emulating while loop
5
4
3
2
1

Emulating Do-While Loop using For Loop

If you have coded in a language like C, you know that the do-while loop construct takes the following form:

// initialize looping var
do {
//something
// update looping var
} while(condition);

The key difference between while and do while loop is that the while loop checks condition upon entry into the loop. The do-while loop, on the other hand, checks the condition upon exit from the loop.

So, in a while loop, if the condition evaluates to false, the loop body never executes. However, in a do-while loop, the loop body executes even if the condition evaluates to false.

Using this information, we can emulate the behavior of a do-while loop:

  • Write an infinite for loop
  • Use an if conditional statement with the correct condition to break out of the loop

Say you want to write a do-while loop where the condition for loop body to execute is num < 0. So you can write a for loop and break out of the loop if num >= 0.

package main

import "fmt"

func main() {
	fmt.Println("Emulating do-while loop")
	num := 5
	for {
		fmt.Println("loop runs...")
		if num >= 0 {
			break
		}
	}
}

💡 Note that executing the loop if num < 0 and breaking out of the loop if num >= 0 are equivalent conditions.

Though the condition num > 0 is initially false (num is 5), the loop body runs once, emulating a do-while loop.

//Output
Emulating do-while loop
loop runs...

Looping Through Arrays Using For Loop

Looping-Through-Arrays-Using-For-Loop

When looping through arrays in Golang using a for loop and range, you can access both the indices and the elements. This works similarly to the enumerate function in Python.

Here, we create numArray, an array of integers. And loop through it using a for loop:

package main

import "fmt"

func main() {
	fmt.Println("Looping through an array")
	numArray := []int{3, 7, 0, 10, 8, 9}
	for idx, num := range numArray {
		fmt.Println("At index", idx, ": ", num)
	}
}

As seen, we’re able to access both the index and the element at each index simultaneously:

//Output
Looping through an array
At index 0 :  3
At index 1 :  7
At index 2 :  0
At index 3 :  10
At index 4 :  8
At index 5 :  9

Using defer in Golang For Loop

In Golang, you can use the defer keyword to defer function calls.

Though used in applications like resource clean up and error handling, it can be helpful to understand how to use defer inside a for loop. Let’s see what happens when we use defer inside the for loop to defer the calls to the Println() function.

package main

import "fmt"

func main() {
	fmt.Println("For loop:")
	num := 5
	for i := 1; i <= num; i++ {
		defer fmt.Println(i)
	}
}

💬 When a function call is deferred, the function call is pushed onto the stack and is executed in LIFO order. This execution happens only after the function that surrounds the defer statement returns.

So fmt.Println(5) gets executed first and fmt.Println(1) gets executed last:

//Output
For loop:
5
4
3
2
1

Conclusion

Here is a summary of what you’ve learned in this tutorial:

  • In Golang, you can create for loops with the syntax: for initialization; condition; update { //loop body}
  • The control flow of the for loop is quite simple. The looping variable is initialized once, the looking condition determines whether or not to execute the loop body, and the update refers to the update of the looping variable after every iteration.
  • The scope of the looping variable is limited to the loop body and is not accessible outside the loop. 
  • Though Golang provides only the for loop construct, you can emulate while and do-while loop behaviors using for loops.
  • A few other applications of for loop include looping through arrays and deferring function calls inside the for loop body.

Next, learn how to use for loops in Python. Happy learning!🎉

  • Bala Priya C
    Author
    Bala Priya is a developer and technical writer from India with over three years of experience in the technical content writing space. She shares her learning with the developer community by authoring tech tutorials, how-to guides, and more…. read more
Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder