Go For Loop
A Go for loop repeatedly executes a block of statements. Go uses the for keyword for traditional counter loops, condition-based loops, infinite loops, and iteration over arrays, slices, strings, maps, and channels.
In this tutorial, you will learn the main forms of the Go for loop, how to use range, how to skip or stop iterations, and how to avoid common loop errors.
Go For Loop Forms at a Glance
- Condition-only loop: repeats while a Boolean condition is true.
- Three-part loop: uses initialization, condition, and update expressions.
- Range loop: iterates over the elements of a supported collection.
- Infinite loop: runs until it reaches a
break,return, or another terminating operation.
1. Go For Loop with a Condition
A condition-only for loop behaves like a while loop in many other programming languages. Go does not have a separate while keyword.
The syntax of for loop in Go, with just condition alone is
for condition {
statement(s)
}
The loop evaluates condition before every iteration. It stops when the condition becomes false.
An example for For Loop with condition is shown below.
example.go
package main
import "fmt"
func main() {
var i int = 0
for i<5 {
fmt.Println(i)
i = i+1
}
}
We have to initialize the control variable, i before the for loop and update it inside the for loop.
0
1
2
3
4
If the update statement is omitted, the condition may remain true and cause an infinite loop.

2. Go For Loop with Initialization, Condition and Update
The three-part form is commonly used when the loop has a counter. Its three components are separated by semicolons, but they are not enclosed in parentheses.
The syntax of Go For Loop statement, with initialization, condition and update sections is
for init; condition; update {
//code
}
initruns once before the first condition check.conditionis evaluated before each iteration.updateruns after each completed iteration.
An example for For Loop with initialization, condition and update is shown below.
example.go
package main
import "fmt"
func main() {
for i:=0; i<5; i++ {
fmt.Println(i)
}
}
The initialization and update of the control variable i happens in the for statement iteslf. This form of for loop is recommended as you would not forget the initialization and update of control variable, which otherwise could result in an infinite loop sometimes.
Here, i := 0 runs once, i < 5 controls whether another iteration can run, and i++ increments the counter after each iteration.
Count Backward with a Go For Loop
The update expression can decrement the counter instead of incrementing it.
package main
import "fmt"
func main() {
for i := 5; i >= 1; i-- {
fmt.Println(i)
}
}
5
4
3
2
1
3. Go For Range Loop over Arrays and Slices
A for range loop is used to iterate over arrays, slices, strings, maps, and channels. For arrays and slices, it can provide both the index and the value at that index.
The syntax of For loop to iterate over a Range is
for x in range {
statement(s)
}
In valid Go code, the range keyword is written after the assignment operator. The general form is shown below.
for index, value := range collection {
statement(s)
}
An example for For Loop over a range is shown below.
example.go
package main
import "fmt"
func main() {
a := [6]int{52, 2, 13, 35, 9, 8}
for i,x:= range a {
fmt.Printf("a[%d] = %d\n", i,x)
}
}
We can access both the index and the element when range is iterated using a for loop. In this example, we get index to i and the element to x during each iteration.
a[0] = 52
a[1] = 2
a[2] = 13
a[3] = 35
a[4] = 9
a[5] = 8
Iterate over Slice Values without the Index
Use the blank identifier _ when the index is not needed.
package main
import "fmt"
func main() {
numbers := []int{10, 20, 30}
for _, number := range numbers {
fmt.Println(number)
}
}
Iterate over Slice Indexes Only
When only one variable is declared in a range loop over a slice or array, that variable receives the index.
package main
import "fmt"
func main() {
items := []string{"pen", "book", "bag"}
for index := range items {
fmt.Println(index)
}
}
Go For Range Loop over a String
When ranging over a string, Go returns the byte index and the Unicode code point, represented by the type rune. This is useful for text that may contain multibyte UTF-8 characters.
package main
import "fmt"
func main() {
text := "Go✓"
for index, character := range text {
fmt.Printf("index=%d character=%c\n", index, character)
}
}
index=0 character=G
index=1 character=o
index=2 character=✓
The indexes are byte positions, so they may not increase by one for every non-ASCII character.
Go For Range Loop over a Map
A range loop over a map returns a key and its corresponding value. The iteration order of a map should not be treated as fixed.
package main
import "fmt"
func main() {
scores := map[string]int{
"Ana": 86,
"Ravi": 91,
}
for name, score := range scores {
fmt.Printf("%s: %d\n", name, score)
}
}
When deterministic output is required, collect the map keys, sort them, and then access the values in the sorted key order.
Infinite For Loop in Go
A for statement without a condition creates an infinite loop.
for {
statement(s)
}
An infinite loop must normally include a controlled exit, such as a break statement.
package main
import "fmt"
func main() {
count := 1
for {
fmt.Println(count)
if count == 3 {
break
}
count++
}
}
Control Go For Loops with Break and Continue
The break statement exits the nearest loop. The continue statement skips the remaining statements in the current iteration and proceeds with the next iteration.
Stop a Go For Loop with Break
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
if i == 4 {
break
}
fmt.Println(i)
}
}
1
2
3
Skip an Iteration with Continue
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
if i == 3 {
continue
}
fmt.Println(i)
}
}
1
2
4
5
Nested For Loops and Labeled Break in Go
A loop can be placed inside another loop. A normal break exits only the innermost loop. A label can be used when execution must leave an outer loop directly.
package main
import "fmt"
func main() {
OuterLoop:
for row := 1; row <= 3; row++ {
for column := 1; column <= 3; column++ {
if row == 2 && column == 2 {
break OuterLoop
}
fmt.Println(row, column)
}
}
}
Common Go For Loop Mistakes
- Forgetting to update a condition variable: a condition-only loop may never terminate.
- Using parentheses around the loop header: Go normally writes
for i := 0; i < n; i++without parentheses. - Using
inwithrange: Go uses:= rangeor= range, not Python-stylein. - Expecting one range variable to contain the value: for arrays and slices, one variable receives the index.
- Depending on map iteration order: map traversal order should not be used for sorted or stable output.
- Modifying only the copied range value: the value variable in a slice range loop is a copy of the element.
Update Slice Elements by Index
To change elements in a slice, update them through their indexes.
package main
import "fmt"
func main() {
numbers := []int{2, 4, 6}
for i := range numbers {
numbers[i] *= 2
}
fmt.Println(numbers)
}
[4 8 12]
Go For Loop Frequently Asked Questions
Does Go have a while loop?
No. Go uses a condition-only for loop in place of a traditional while loop, such as for count < 10.
How do you loop over a slice in Go?
Use for index, value := range slice when both values are required. Use for _, value := range slice for values only, or for index := range slice for indexes only.
How do you create an infinite loop in Go?
Write for { ... } without a condition. Include a controlled exit unless the loop is intentionally designed to run for the lifetime of the program.
What does range return in a Go for loop?
The returned values depend on the operand. Arrays and slices provide index and value, strings provide byte index and rune, maps provide key and value, and channels provide successive received values.
How do you exit a Go for loop early?
Use break to exit the nearest loop. Use a labeled break to exit a specific enclosing loop.
Go For Loop Editorial QA Checklist
- Confirm every Go loop header omits unnecessary parentheses.
- Verify condition-only examples update the variable used in the condition.
- Check that all
rangeexamples use valid:= rangeor= rangesyntax. - Confirm output blocks match the order produced by arrays, slices, and counter loops.
- Do not present map iteration output as having a guaranteed order.
- Verify string range examples describe byte indexes and Unicode runes correctly.
Go For Loop Summary
Go uses one for statement for several looping patterns. Use a condition-only loop when repetition depends on a Boolean expression, a three-part loop for counters, for range for collections, and for {} for an intentional infinite loop. Use break and continue to control execution inside the loop.
In this Go Tutorial, we learned about For Loop in Go, and its different forms for different types of data and scenarios.
TutorialKart.com