Doing Things Over and Over Again
In our last part, we taught our code how to make decisions using if
and switch
. Now, let's teach it how to perform tasks repeatedly without us having to copy and paste our code. This process is called looping.
Many programming languages have several types of loops (while
, do-while
, for
, forEach
). Go simplifies this dramatically.
In Go, there is only one loop: the for
loop. But it's incredibly versatile and can handle every looping scenario you need. Let's explore its three main forms.
1. The Classic for
Loop
This is the most traditional form of a for
loop, and you'll recognize it if you've used languages like C++, Java, or JavaScript. It's perfect when you know exactly how many times you want to repeat an action.
It consists of three parts, separated by semicolons:
- The init statement:
i := 0
(Initializes a counter. Runs once at the very beginning). - The condition expression:
i < 5
(Checked before every loop. Iftrue
, the loop continues). - The post statement:
i++
(Runs at the end of every loop iteration, usually to increment the counter).
Analogy: An assembly line worker who has been told to assemble exactly 5 boxes.
Code Example
package main
import "fmt"
func main() {
// This loop will run 5 times (for i = 0, 1, 2, 3, 4)
for i := 0; i < 5; i++ {
fmt.Println("Assembling box number:", i)
}
}
2. The for
Loop as a while
Loop
What if you don't know how many times to loop, but you know the condition to stop? In other languages, you'd use a while
loop. Go handles this with a simplified for
loop.
You just provide the condition, and the loop will run as long as that condition is true
.
Analogy: Running on a treadmill. You don't know how many steps you'll take, but you'll keep running until you've burned 100 calories. The condition is caloriesBurned < 100
.
Code Example
package main
import "fmt"
func main() {
// This loop acts like a 'while' loop
// It will run as long as 'number' is less than or equal to 5
number := 1
for number <= 5 {
fmt.Println("The number is:", number)
number++ // Important: Update the variable to avoid an infinite loop!
}
}
3. The for range
Loop: Iterating Over Collections
This is the most idiomatic and powerful way to loop over collections like slices and maps. It's Go's version of a forEach
loop.
Analogy: Going through your grocery bag and looking at each item one by one.
Code Example with a Slice
When used with a slice, for range
gives you the index
and the value
of each element.
package main
import "fmt"
func main() {
fruits := []string{"Apple", "Banana", "Cherry"}
for index, fruit := range fruits {
fmt.Printf("Fruit at index %d is %s\n", index, fruit)
}
// If you only need the value, you can ignore the index with an underscore (_)
fmt.Println("\nJust the fruit names:")
for _, fruit := range fruits {
fmt.Println(fruit)
}
}
Code Example with a Map
When used with a map, it gives you the key
and the value
of each pair.
package main
import "fmt"
func main() {
userProfile := map[string]string{
"name": "Budi",
"city": "Jakarta",
}
for key, value := range userProfile {
fmt.Printf("%s: %s\n", key, value)
}
}
Conclusion
Even with just one loop keyword, Go provides all the power you need to handle any repetitive task. You've now learned the three essential patterns:
- The classic
for
loop for a fixed number of iterations. - The conditional
for
loop that acts like awhile
loop. - The
for range
loop for iterating over collections.
Mastering loops is a huge step in becoming a proficient programmer. In our next part, we'll learn how to organize our code into clean, reusable blocks called Functions. See you there!
Top comments (0)