Loops in Go (for, range, labeled loops)
Go provides the for loop as its primary looping construct. Understanding different loop patterns is essential for effective Go programming.
Basic For Loop
Traditional For Loop
package main
import "fmt"
func main() {
// Traditional C-style for loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// Output: 0 1 2 3 4
}
While-Style Loop
package main
import "fmt"
func main() {
// While-style loop (condition only)
i := 0
for i < 5 {
fmt.Println(i)
i++
}
}
Infinite Loop
package main
import "fmt"
func main() {
// Infinite loop (must break manually)
i := 0
for {
fmt.Println(i)
i++
if i >= 5 {
break
}
}
}
Range Iteration
Range Over Slices
package main
import "fmt"
func main() {
numbers := []int{10, 20, 30, 40, 50}
// Range with index and value
for i, v := range numbers {
fmt.Printf("Index: %d, Value: %d\n", i, v)
}
// Range with index only
for i := range numbers {
fmt.Printf("Index: %d\n", i)
}
// Range with value only
for _, v := range numbers {
fmt.Printf("Value: %d\n", v)
}
}
Range Over Maps
package main
import "fmt"
func main() {
person := map[string]int{
"Alice": 30,
"Bob": 25,
"Charlie": 35,
}
// Range over map
for name, age := range person {
fmt.Printf("%s: %d\n", name, age)
}
// Range with key only
for name := range person {
fmt.Printf("Name: %s\n", name)
}
}
Range Over Strings
package main
import "fmt"
func main() {
str := "Hello"
// Range over string (returns rune)
for i, ch := range str {
fmt.Printf("Index: %d, Char: %c, Code: %d\n", i, ch, ch)
}
}
Range Over Channels
package main
import "fmt"
func main() {
ch := make(chan int, 3)
ch <- 1
ch <- 2
ch <- 3
close(ch)
// Range over channel
for value := range ch {
fmt.Println(value)
}
}
Break and Continue
Break Statement
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i == 5 {
break // Exit loop
}
fmt.Println(i)
}
// Output: 0 1 2 3 4
}
Continue Statement
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
if i == 2 {
continue // Skip to next iteration
}
fmt.Println(i)
}
// Output: 0 1 3 4
}
Labeled Loops
Break with Label
package main
import "fmt"
func main() {
// Labeled loop
OuterLoop:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if i == 1 && j == 1 {
break OuterLoop // Break outer loop
}
fmt.Printf("i=%d, j=%d\n", i, j)
}
}
}
Continue with Label
package main
import "fmt"
func main() {
// Labeled loop with continue
OuterLoop:
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if j == 1 {
continue OuterLoop // Continue outer loop
}
fmt.Printf("i=%d, j=%d\n", i, j)
}
}
}
Loop Patterns
Iterating with Index
package main
import "fmt"
func main() {
items := []string{"apple", "banana", "cherry"}
for i := 0; i < len(items); i++ {
fmt.Printf("%d: %s\n", i, items[i])
}
}
Iterating Backwards
package main
import "fmt"
func main() {
items := []string{"apple", "banana", "cherry"}
for i := len(items) - 1; i >= 0; i-- {
fmt.Printf("%d: %s\n", i, items[i])
}
}
Filtering During Iteration
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for _, n := range numbers {
if n%2 == 0 {
fmt.Println(n) // Print even numbers
}
}
}
Best Practices
โ Good: Use Range for Iteration
// DO: Use range for cleaner iteration
for i, v := range items {
fmt.Println(i, v)
}
โ Bad: Manual Index Management
// DON'T: Manually manage indices
for i := 0; i < len(items); i++ {
fmt.Println(i, items[i])
}
โ Good: Use Blank Identifier
// DO: Use blank identifier for unused values
for _, v := range items {
fmt.Println(v)
}
โ Bad: Unused Variables
// DON'T: Declare unused variables
for i, v := range items {
fmt.Println(v) // i is unused
}
โ Good: Clear Loop Conditions
// DO: Use clear, readable conditions
for i := 0; i < len(items); i++ {
// ...
}
Summary
Go’s loop constructs provide:
- For loops in multiple styles
- Range iteration for collections
- Break and continue for loop control
- Labeled loops for nested loop control
- Clean syntax for common patterns
These tools enable efficient and readable iteration in Go programs.
Comments