Introduction
The for-range
construct in Go is a versatile looping mechanism that simplifies the process of iterating over elements in various data structures such as arrays, slices, maps, strings, and channels. This guide will cover the syntax and usage of the for-range
loop in Go, with examples for different types of data structures.
Syntax
The for-range
loop iterates over elements in a data structure, assigning the index (or key) and value to variables.
Syntax:
for index, value := range collection {
// code to execute for each element
}
If you only need the value, you can use the underscore (_
) to ignore the index.
Syntax:
for _, value := range collection {
// code to execute for each value
}
Examples
Iterating Over an Array or Slice
When iterating over an array or slice, the for-range
loop provides both the index and the value of each element.
Example:
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Println("Index:", index, "Value:", value)
}
}
Iterating Over a String
When iterating over a string, the for-range
loop provides the index and the Unicode code point (rune) of each character.
Example:
package main
import "fmt"
func main() {
text := "Hello"
for index, char := range text {
fmt.Printf("Index: %d, Character: %c\n", index, char)
}
}
Iterating Over a Map
When iterating over a map, the for-range
loop provides both the key and the value of each entry.
Example:
package main
import "fmt"
func main() {
ages := map[string]int{"Alice": 25, "Bob": 30, "Charlie": 35}
for key, value := range ages {
fmt.Println("Key:", key, "Value:", value)
}
}
Iterating Over a Channel
When iterating over a channel, the for-range
loop receives values from the channel until it is closed.
Example:
package main
import "fmt"
func main() {
ch := make(chan int, 3)
ch <- 1
ch <- 2
ch <- 3
close(ch)
for value := range ch {
fmt.Println("Value:", value)
}
}
Using Only the Value
If you only need the value and not the index or key, you can use an underscore (_
) to ignore the index or key.
Example:
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
for _, value := range numbers {
fmt.Println("Value:", value)
}
}
Nested for-range Loops
You can use nested for-range
loops to iterate over multi-dimensional data structures such as slices of slices.
Example:
package main
import "fmt"
func main() {
matrix := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
for i, row := range matrix {
for j, value := range row {
fmt.Printf("matrix[%d][%d] = %d\n", i, j, value)
}
}
}
Conclusion
The for-range
construct in Go provides a convenient and powerful way to iterate over various data structures, including arrays, slices, maps, strings, and channels. By understanding and using the for-range
loop, you can write cleaner and more readable code for handling collections and data structures. This construct is essential for efficient and effective iteration in Go programs.