VOOZH about

URL: https://thenewstack.io/golang-how-to-write-a-for-loop/

⇱ Golang: How to Write a For Loop - The New Stack


TNS
SUBSCRIBE
Join our community of software engineering leaders and aspirational developers. Always stay in-the-know by getting the most important news and exclusive content delivered fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter in the past. Click the button below to open the re-subscribe form in a new tab. When you're done, simply close that tab and continue with this form to complete your subscription.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!

We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.

What’s next?

Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.

Follow TNS on your favorite social media networks.

Become a TNS follower on LinkedIn.

Check out the latest featured and trending stories while you wait for your first TNS newsletter.

PREV
1 of 2
NEXT
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
Thanks for your opinion! Subscribe below to get the final results, published exclusively in our TNS Update newsletter:
NEW! Try Stackie AI
From clobbered drafts to real-time sync
Apr 14th 2026 10:00am, by David Moore
TypeScript 6.0 RC arrives as a bridge to a faster future
Mar 14th 2026 9:00am, by Darryl K. Taft
Mastra empowers web devs to build AI agents in TypeScript
Jan 28th 2026 11:00am, by Loraine Lawson
2024-04-16 17:00:28
Golang: How to Write a For Loop
Operations

Golang: How to Write a For Loop

The for loop is the most basic type of loop in the Go programming language, but it's one you'll use quite often. Here's how it works.
Apr 16th, 2024 5:00pm by Jack Wallen
👁 Featued image for: Golang: How to Write a For Loop

Programming Loops: You know them, you love them. Either that or you don’t know them and you’re unsure just how important they are to nearly all programming languages.

Golang is no exception and uses the for loop to repeat a block of code until a given condition is met. The for loop is actually the most basic type of loop in Go but it’s one you’ll use quite often.

The reasons you might make use of a for loop are varied (depending on your needs). For example, you might want to print out a statement multiple times. Instead of writing the same fmt.print() statement over and over, you could use a for loop to take care of the process.

A for loop consists of the following bits:

  • The initialization – initializes or declares variables.
  • The condition – what is used to evaluate the condition. As long as the condition remains true, the loop is executed.
  • The update – updates the value of the initialization each time the loop executes.
  • Statement(s) – what is executed

The basic syntax of the for loop looks like this:

for initialization; condition; update {
   statement(s)
}

Remember our printing example above? Let’s say we want to print out New Stack Rocks 10 times. Yes, we could write a Go program that would simply use the fmt.Println() function 10 times like this:

package main
import "fmt"

func main() {

   fmt.Println("New Stack Rocks")
   fmt.Println("New Stack Rocks")
   fmt.Println("New Stack Rocks")
   fmt.Println("New Stack Rocks")
   fmt.Println("New Stack Rocks")
   fmt.Println("New Stack Rocks")
   fmt.Println("New Stack Rocks")
   fmt.Println("New Stack Rocks")
   fmt.Println("New Stack Rocks")
   fmt.Println("New Stack Rocks")

}

If you ran the above code, it would, in fact, print out the following:

New Stack Rocks
New Stack Rocks
New Stack Rocks
New Stack Rocks
New Stack Rocks
New Stack Rocks
New Stack Rocks
New Stack Rocks
New Stack Rocks
New Stack Rocks

Of course, you don’t want to do things that way. Not only is it inefficient, but it’s also a great way to introduce errors and it’s not very effective. Instead, we’ll do that same thing with a for loop like so:

package main
import "fmt"

func main() {

   for i := 1; i  <= 10; i++ {
      fmt.Println("New Stack Rocks")
   }

}

You already know that we call the main package and import fmt with the first two lines. The next line func main() initializes the main package. Our for loop is then created with the following:

  • i := 1 – the initialization that sets i to 1.
  • i <= 10 – the condition that says as long as i is less than or equal to 10, continue.
  • i++ – the update that adds 1 to the previous value of I.
  • fmt.Println(“New Stack Rocks”) – our print statement that is executed so long as i <= 10.

Along those same lines, you could even create an infinite loop. Why would you want to use an infinite loop? They actually have their purposes. For example, you might want to write application code that has to keep running until it is stopped, such as a web server or an application that requires continuous user input until the application is manually stopped.

An infinite loop can be accomplished with a for loop minus the condition statement. So, a for loop might look something like this:

for {
   fmt.Println("New Stack Rocks")
}

The entire application could look like this:

package main
import "fmt"

func main() {
   for {
       fmt.Println("New Stack Rocks")
  }

}

If you run the above code, it will continue printing out New Stack Rocks, until you kill it with something like the Ctrl+C keyboard shortcut.

There’s another really cool trick with the for loop which includes the range keyword. The range keyword is used to iterate over elements within a data structure. Range can be used with arrays, slices, strings, maps, and channels. Let me show you an example of using the range keyword on a for loop iterating over a string.

The for loop with the range keyword will look something like this:

for i, ch := range "New Stack Rocks" {
   fmt.Printf("%#U starts a position %d\n", ch, i)

What this for loop does is iterate through the string and prints out the letter and position until it completes. The full code looks like this:

package main
import "fmt"

func main() {
  for i, ch := range "New Stack Rocks" {
   fmt.Printf("%#U starts a position %d\n", ch, i)
  } 

}

If you run this, the output would be:

U+004E ‘N’ starts a position 0
U+0065 ‘e’ starts a position 1
U+0077 ‘w’ starts a position 2
U+0020 ‘ ‘ starts a position 3
U+0053 ‘S’ starts a position 4
U+0074 ‘t’ starts a position 5
U+0061 ‘a’ starts a position 6
U+0063 ‘c’ starts a position 7
U+006B ‘k’ starts a position 8
U+0020 ‘ ‘ starts a position 9
U+0052 ‘R’ starts a position 10
U+006F ‘o’ starts a position 11
U+0063 ‘c’ starts a position 12
U+006B ‘k’ starts a position 13
U+0073 ‘s’ starts a position 14

Notice we use fmt.Printf() instead of fmt.Println(). The reason for this is Printf allows you to format numbers, variables, and strings, whereas Println simply prints the line as is. If you used fmt.Println instead, the output would be:

%#U starts a position %d 78 0

Clearly, that’s not correct, so we have to use fmt.Printf() instead.

And that is how you write a for loop in your favorite new language. Now you’ve seen how it works, are you ready to take it to the next level? If so, ready, set, Go!

TRENDING STORIES
Jack Wallen is what happens when a Gen Xer mind-melds with present-day snark. Jack is a seeker of truth and a writer of words with a quantum mechanical pencil and a disjointed beat of sound and soul. Although he resides...
Read more from Jack Wallen
SHARE THIS STORY
TRENDING STORIES
TNS owner Insight Partners is an investor in: Statement.
SHARE THIS STORY
TRENDING STORIES
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.