Introduction
The for
loop is the only loop construct in Go, but it is versatile enough to handle a wide range of looping scenarios. In this chapter, you will learn the syntax and usage of the for
loop in Go, with examples to illustrate different types of loops.
Basic Syntax
Simple for Loop
A simple for
loop consists of three components: initialization, condition, and post statement. The loop executes as long as the condition is true.
Syntax:
for initialization; condition; post {
// code to execute
}
Example:
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i) // Output: 0 1 2 3 4
}
}
The for Loop with Only Condition
You can omit the initialization and post statements, creating a loop that behaves like a while
loop in other languages.
Example:
package main
import "fmt"
func main() {
i := 0
for i < 5 {
fmt.Println(i) // Output: 0 1 2 3 4
i++
}
}
Infinite Loop
You can create an infinite loop by omitting all three components of the for
loop.
Example:
package main
import "fmt"
func main() {
i := 0
for {
fmt.Println(i)
i++
if i == 5 {
break // Breaks out of the loop when i is 5
}
}
}
for-range Loop
The for-range
loop iterates over elements in a variety of data structures such as arrays, slices, maps, strings, and channels.
Array or Slice
Example:
package main
import "fmt"
func main() {
arr := []int{1, 2, 3, 4, 5}
for index, value := range arr {
fmt.Println("Index:", index, "Value:", value)
}
}
String
When iterating over a string, the for-range
loop returns the index and the Unicode code point (rune) of each character.
Example:
package main
import "fmt"
func main() {
str := "Hello"
for index, char := range str {
fmt.Printf("Index: %d, Char: %c\n", index, char)
}
}
Map
Example:
package main
import "fmt"
func main() {
myMap := map[string]int{"one": 1, "two": 2, "three": 3}
for key, value := range myMap {
fmt.Println("Key:", key, "Value:", value)
}
}
Channel
Example:
package main
import "fmt"
func main() {
ch := make(chan int, 5)
ch <- 1
ch <- 2
ch <- 3
close(ch)
for value := range ch {
fmt.Println("Value:", value)
}
}
Nested for Loops
You can use nested for
loops to iterate over multi-dimensional data structures.
Example:
package main
import "fmt"
func main() {
matrix := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
for i := range matrix {
for j := range matrix[i] {
fmt.Print(matrix[i][j], " ")
}
fmt.Println()
}
}
Using Break and Continue
Break
The break
statement exits the nearest enclosing loop.
Example:
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i == 5 {
break // Exit the loop when i is 5
}
fmt.Println(i)
}
}
Continue
The continue
statement skips the remaining code in the current iteration and moves to the next iteration of the loop.
Example:
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i%2 == 0 {
continue // Skip the rest of the loop for even numbers
}
fmt.Println(i) // Output: 1 3 5 7 9
}
}
Conclusion
The for
loop in Go is a powerful and flexible tool for iterating over data. By understanding how to use simple for
loops, for-range
loops, nested loops, and the break
and continue
statements, you can effectively control the flow of your program and perform complex iterations. The for
loop is the cornerstone of repetition in Go, making it an essential concept to master.