Loops: for (Range, Break, Continue & Labels) - Go Tutorial for Beginners #8
Video: Loops: for (Range, Break, Continue & Labels) - Go Tutorial for Beginners #8 by Taught by Celeste AI - AI Coding Coach
Watch full page →Loops: for (Range, Break, Continue & Labels) - Go Tutorial for Beginners #8
Go has a single looping construct: the for loop, which is extremely versatile. In this lesson, you will learn how to use traditional three-part loops, while-style loops, and the powerful range form to iterate over slices, maps, and strings. You'll also discover how to control loop flow with break, continue, and labeled statements for nested loops.
Code
package main
import "fmt"
func main() {
// Traditional for loop: init; condition; post
for i := 0; i < 5; i++ {
fmt.Println("Traditional loop iteration:", i)
}
// While-style loop: condition only
n := 3
for n > 0 {
fmt.Println("While-style loop, n =", n)
n--
}
// Range loop over a slice
nums := []int{10, 20, 30}
for index, value := range nums {
fmt.Printf("Slice index %d has value %d\n", index, value)
}
// Range loop over a map
colors := map[string]string{"red": "#FF0000", "green": "#00FF00"}
for key, val := range colors {
fmt.Printf("Map key %s has value %s\n", key, val)
}
// Range loop over a string (iterates over runes)
str := "Go!"
for i, c := range str {
fmt.Printf("Character at position %d is %q\n", i, c)
}
// Using break and continue
for i := 0; i < 10; i++ {
if i == 5 {
fmt.Println("Breaking at i =", i)
break // exit loop early
}
if i%2 == 0 {
continue // skip even numbers
}
fmt.Println("Odd number:", i)
}
// Labeled loops for nested control
outer:
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {
if i*j > 4 {
fmt.Println("Breaking out of both loops at", i, j)
break outer // break outer loop
}
fmt.Printf("i=%d, j=%d\n", i, j)
}
}
}
Key Points
- Go’s only loop construct is
for, which can be used like a traditional for loop, a while loop, or a range-based loop. - The
rangekeyword simplifies iterating over slices, maps, and strings by providing index/key and value pairs. breakexits the nearest enclosing loop, whilecontinueskips the current iteration and proceeds to the next.- Labeled loops allow breaking or continuing outer loops from within nested loops for finer control flow.
- Looping over strings with
rangeiterates over Unicode code points (runes), not bytes.