Go For Loops Explained with Simple Examples

Updated 5 min read
Go For Loops featured image: cards showing the three-part loop, range, break and continue

Go for loops let your program repeat a task without writing the same code again and again. In this post, you will learn every loop style Go offers. Each one comes with a short example that you can run yourself.

Loops build on the last lesson, because every loop checks a condition before each round. So if true and false checks still feel new, first read if, else and switch in Go. You will also use <=, ++ and += from operators in Go with simple examples.

What Are Go For Loops?

A loop runs the same block of code many times. Each single run is called an iteration. Think of a teacher calling roll: she reads one name, then the next, and stops after the last student.

Many languages have for, while and do while loops. However, Go keeps things simple. It has only one loop keyword, for, and you shape it in different ways. As a result, Go for loops cover every repeat job you will ever need.

The Three-Part Loop

for i := 1; i <= 5; i++ {
	fmt.Println("Count:", i)
}
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5

Among all Go for loops, this is the one you will see most often. It has three parts separated by semicolons, and like if, it needs no brackets around them.

How Each Part Works

  1. Init (i := 1) runs once, before the loop starts.
  2. Condition (i <= 5) is checked before every round.
  3. Body is the code inside the braces, and it runs while the condition is true.
  4. Post (i++) runs after each round, and then Go checks the condition again.
Go For Loops diagram showing the init, condition, body and post steps of a three-part loop

Init runs once, then condition, body and post repeat until the condition becomes false.

Go For Loops Without a Counter

Sometimes you do not know how many rounds you need. In that case, you can drop the init and post parts and keep only the condition.

The While-Style Loop

n := 1
for n < 100 {
	n = n * 2
}
fmt.Println(n) // 128

This loop keeps doubling n while it stays below 100. In other languages, you would call this a while loop. Go simply uses for with one condition.

The Infinite Loop with break

tries := 0
for {
	tries++
	if tries == 3 {
		fmt.Println("Got it on try", tries)
		break
	}
}
// Got it on try 3

A for with nothing after it runs forever. So you must stop it yourself with break, which exits the loop at once. Servers often use this pattern to keep listening for new requests.

Skipping Steps in Go For Loops with continue

for i := 1; i <= 6; i++ {
	if i%2 == 0 {
		continue
	}
	fmt.Print(i, " ")
}
// 1 3 5

The continue keyword skips the rest of the current round and jumps to the next one. Here it skips every even number, so only odd numbers print. In short, break stops the loop, while continue only skips one step.

Looping with range in Go For Loops

The range keyword walks through a collection one item at a time. Think of it as a cashier scanning each product in your basket.

Range over a Slice

fruits := []string{"apple", "mango", "banana"}
for i, fruit := range fruits {
	fmt.Println(i, fruit)
}
// 0 apple
// 1 mango
// 2 banana

total := 0
for _, price := range []int{40, 25, 35} {
	total += price
}
fmt.Println("Total:", total) // Total: 100

Range gives you two values: the position, called the index, and the item itself. If you do not need the index, write an underscore _ instead. The underscore tells Go to throw that value away.

Range over a Number or a String

for i := range 3 {
	fmt.Print(i, " ")
}
// 0 1 2

for i, ch := range "Go!" {
	fmt.Println(i, string(ch))
}
// 0 G
// 1 o
// 2 !

Since Go 1.22, range 3 counts from 0 up to 2. Also, range over a string gives you each character, which Go calls a rune.

Breaking Out of Nested Go For Loops

outer:
	for i := 1; i <= 3; i++ {
		for j := 1; j <= 3; j++ {
			if i*j == 4 {
				break outer
			}
			fmt.Println(i, j)
		}
	}
// 1 1, 1 2, 1 3, 2 1 (each on its own line)

A plain break exits only the inner loop. However, a label like outer: lets you exit both loops in one step. Use labels sparingly, since they can make code harder to follow.

Common Mistakes with Go For Loops

Error you seeWhy it happensHow to fix it
declared and not used: iThe range index is never read.Replace i with _.
panic: runtime error: index out of range [3] with length 3The loop used i <= len(n).Use i < len(n) or range.
Program never stopsThe condition never turns false.Update the counter or add break.

The second mistake is called an off-by-one error. Positions start at 0, so the last valid index is always one less than the length. Loop questions like this also come up often in my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • Go for loops are the only loop in Go, and you shape them in different ways.
  • The three-part loop has init, condition and post.
  • A loop with only a condition works like a while loop.
  • Use break to stop and continue to skip one round.
  • Range walks through slices, strings and numbers, giving index and value.

What’s Next?

Now you can repeat work with loops. Next, we will package that work into reusable blocks called functions, so you can call the same logic anywhere.

Coming soon: Go Functions Explained for Beginners