Skip to main content

Command Palette

Search for a command to run...

Looping Construct in Go

Updated
1 min read
Looping Construct in Go
P

👋 Hey there!

I'm a community-driven software engineer, and I absolutely love diving into the world of cloud-native development and exploring the endless possibilities of open-source technologies. 💻

My skill set revolves around Kubernetes, GoLang, Python, Docker, and other fascinating container technologies. 🚀 And hey, just to add to the mix, I'm also CKA certified! 🎓

But you know what? My journey doesn't stop at coding. I have a genuine passion for technical evangelism. 🎤 I've had the privilege to speak at world-renowned events, sharing my knowledge and insights with others. It's such an exhilarating experience! And when I'm not on stage, you can find me pouring my thoughts into engaging technical blogs. 📝

If you've made it this far and you're intrigued by what you've read, let's not leave it at that! Reach out, and let's connect. Who knows what exciting opportunities may be awaiting us? 😊

Go has only one looping construct, the for loop.

Basic for loop

The basic for loop has three components separated by semicolons:

  • init statement: i := 0 exec before 1st iteration

  • condition expression: i < n eval on every iteration

  • post statement: i++ exec after each iteration

The expression is not surrounded by parentheses ( ) but the braces { } around a set of instructions are required.

for i := 0; i < n; i++ {
    //business logic
    //set of instructions
}

Init and post statements are optional.

for ; i < n; {
    //business logic
}

For is also a while() loop

for i < n {
    //business logic
}

Infinite loop

for {
    //business logic
}

Example

package main
import "fmt"

func main() {
    for i := 0; i < 5; i++ {fmt.Printf("Iteration number: %d\n", i)}
}

Run this code in Go Playground

Iteration number: 0
Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4

Thank you for reading this blog, and please give your feedback in the comment section below.

More from this blog

pratikjagrut.space

32 posts