Go — Loops
For loop
Go has only one loop construct — for:
package main
import "fmt"
func main() {
// Traditional for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// While-style
count := 0
for count < 5 {
fmt.Println(count)
count++
}
// Infinite loop
for {
break
}
}
Range
Iterate over slices, arrays, maps, and strings:
// Slice
nums := []int{10, 20, 30, 40, 50}
for i, v := range nums {
fmt.Printf("Index %d: %d\n", i, v)
}
// Map
ages := map[string]int{"Alice": 30, "Bob": 25}
for name, age := range ages {
fmt.Printf("%s: %d\n", name, age)
}
// String (iterates by rune)
for i, r := range "Hello" {
fmt.Printf("Index %d: %c\n", i, r)
}
// Ignore index
for _, v := range nums {
fmt.Println(v)
}
// Ignore value
for i := range nums {
fmt.Println(i)
}
break and continue
// break: exit the loop
for i := 0; i < 100; i++ {
if i == 5 {
break
}
fmt.Println(i)
}
// continue: skip to next iteration
for i := 0; i < 10; i++ {
if i%2 == 0 {
continue
}
fmt.Println(i)
}
Labeled break/continue
outer:
for i := 0; i < 5; i++ {
for j := 0; j < 5; j++ {
if i*j > 10 {
break outer
}
fmt.Printf("(%d,%d) ", i, j)
}
fmt.Println()
}
Common patterns
// Sum
sum := 0
for i := 1; i <= 100; i++ {
sum += i
}
// Find
for _, v := range nums {
if v == target {
fmt.Println("Found:", v)
break
}
}
// Filter
var evens []int
for _, v := range nums {
if v%2 == 0 {
evens = append(evens, v)
}
}
Mini Practice
Write Go code that:
- Uses
forto print numbers 1-20 - Uses
rangeto iterate a map - Uses labeled break to exit nested loops
- Filters a slice using a loop
Up Next
In the next lesson, you'll learn about Functions — defining and using functions in Go.
Related Topics
Frequently Asked Questions about Loops
What is Loops in Go?
Loops is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Loops?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Loops.
Why is Loops important in Go?
Loops is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.