The for Loop in Go
When you need to run the same block of code repeatedly—changing a value each time—loops become your best friend. Every pass through the loop is called an iteration.
In Go, the workhorse for repetition is the for loop. It can be structured with up to three components:
syntex:
for initialization; condition; post {
// code executed on every iteration
}
- initialization – Sets things up before the first iteration (e.g., declaring and initializing a counter).
- condition – Evaluated before each run; as long as it’s true, the loop continues.
- post – Executes after each iteration (commonly used to update the counter).
Understanding the three parts of a for loop
Initialization (statement 1)
- Runs once, right before the first iteration. It usually sets the starting value of the loop counter.
Condition check (statement 2)
- Evaluated before every iteration. If it’s true, the loop body executes; if it’s false, the loop stops.
Post‑iteration update (statement 3)
- Executes after each pass through the loop, typically to increment or otherwise update the loop counter.
Tip: These operations are mandatory for controlling the loop’s flow, but they don’t all have to sit inside the for header. You can place any—or all—of them elsewhere in your code as long as the same logic is performed.
For Loop Example in Go
Example 1: Printing Numbers from 0 to 4
The following Go program uses a for loop to print numbers from 0 to 4:
package main
import ("fmt")
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
Output:
0
1
2
3
4
Explanation:
- i := 0 initializes the loop counter to 0.
- i < 5 is the loop condition; the loop runs as long as this condition is true.
- i++ increments the counter by 1 after each iteration.
- fmt.Println(i) prints the current value of i.
Example 2:
ackage main
import "fmt"
func main() {
for i := 0; i <= 100; i += 10 {
fmt.Println(i)
}
}
output:
0
10
20
30
40
50
60
70
80
90
100
Explanation:
- i := 0 – Initializes the loop counter i with a starting value of 0.
- i <= 100 – The loop will keep running as long as i is less than or equal to 100.
- i += 10 – Increases the value of i by 10 after each loop iteration.
Using the continue Statement in Go
- The continue statement is used inside loops to skip the current iteration and jump directly to the next one. When continue is encountered, the rest of the code inside the loop for that iteration is skipped.
Example: Skipping a Value
In the example below, the loop skips the value 3 and continues with the next iteration:
package main
import ("fmt")
func main() {
for i := 0; i < 5; i++ {
if i == 3 {
continue
}
fmt.Println(i)
}
}
Output:
0
1
2
4
The break Statement
- break lets you immediately exit the nearest enclosing loop, skipping any remaining iterations.
Example:
The following program stops the loop when i reaches 3:
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
if i == 3 {
break // leave the loop
}
fmt.Println(i)
}
}
Output
0
1
2
Tip: Both break and continue are typically paired with conditions to fine‑tune how and when your loops run.
Nested Loops in Go
In Go, you can nest one loop inside another. For every cycle of the outer loop, the inner loop will run from start to finish. This is useful when you need to combine or compare elements from two collections.
Example
package main
import "fmt"
func main() {
adjectives := [2]string{"big", "tasty"}
fruits := [3]string{"apple", "orange", "banana"}
// Outer loop: cycles through each adjective
for i := 0; i < len(adjectives); i++ {
// Inner loop: cycles through each fruit
for j := 0; j < len(fruits); j++ {
fmt.Println(adjectives[i], fruits[j])
}
}
}
Output
big apple
big orange
big banana
tasty apple
tasty orange
tasty banana
range in Go
range is Go’s built‑in helper for looping over arrays, slices, and maps. Each iteration supplies two things:
1.The current index (or key, if you’re ranging over a map).
2.The corresponding value.
Syntax
for index, value := range collection {
// code executed on every iteration
}
Both variables are optional—underscore (_) can be used if you need only one of them.
Example 1: looping through an array
package main
import "fmt"
func main() {
fruits := [3]string{"apple", "orange", "banana"}
for idx, val := range fruits {
fmt.Printf("%d\t%s\n", idx, val)
}
}
Output
0 apple
1 orange
2 banana
Example 2: Ignoring the index
If you only need each element’s value, use the blank identifier (_) to discard the index:
package main
import "fmt"
func main() {
fruits := [3]string{"apple", "orange", "banana"}
for _, val := range fruits {
fmt.Println(val)
}
}
Output
apple
orange
banana
Example 3: Printing Only the Indexes
- Sometimes you only need the position of each element and not the element itself. In that case, replace the value variable with the blank identifier (_).
- Here, idx captures the index while _ discards the value:
package main
import "fmt"
func main() {
fruits := [3]string{"apple", "orange", "banana"}
// Loop through the array, ignoring the value
for idx, _ := range fruits {
fmt.Println(idx)
}
}
Output
0
1
2