Working with arrays is a common task in programming, and Go (often referred to as Golang) provides several ways to iterate over arrays, primarily through the use of loops. Let's explore these different loop techniques from basic to advanced examples.
1. Basic Iteration with a For Loop
The most straightforward way to iterate over an array in Go is by using a simple for loop. Here's how it works:
package main
import "fmt"
func main() {
// Define an array
fruits := [3]string{"apple", "banana", "cherry"}
// Basic for loop to iterate over an array
for i := 0; i < len(fruits); i++ {
fmt.Println(fruits[i])
}
}
This code defines an array of strings called fruits and uses a traditional for loop to print each element.
2. Using the Range Keyword
Go provides a more concise way to iterate over arrays using range. This method is often preferred because it's more succinct and less error-prone:
package main
import "fmt"
func main() {
fruits := [3]string{"apple", "banana", "cherry"}
// Using range to iterate over an array
for index, value := range fruits {
fmt.Printf("%d: %s\n", index, value)
}
}
In this example, for each iteration, range returns both the index and the value of the element from the array.
3. Ignoring the Index with Underscore
If you don't need the index, Go allows you to ignore it using an underscore (_):
package main
import "fmt"
func main() {
fruits := [3]string{"apple", "banana", "cherry"}
// Ignoring the index
for _, value := range fruits {
fmt.Println(value)
}
}
This simplifies the code when only element values are needed.
4. Modifying Array Elements
With arrays being fixed-size, you may sometimes want to modify elements during iteration without changing the size:
package main
import "fmt"
func main() {
nums := [3]int{1, 2, 3}
for i := range nums {
nums[i] *= 2
}
fmt.Println(nums) // Output: [2, 4, 6]
}
This example doubles each element in the nums array by directly modifying them through their indexes.
5. Advanced Iteration: Multi-Dimensional Arrays
In some complex scenarios, you might work with multi-dimensional arrays:
package main
import "fmt"
func main() {
matrix := [2][3]int{{1, 2, 3}, {4, 5, 6}}
for i, row := range matrix {
fmt.Printf("Row %d: ", i)
for _, value := range row {
fmt.Printf("%d ", value)
}
fmt.Println()
}
}
This code snippet defines a 2x3 matrix and iterates over each row and element, showcasing nested iteration.
Using loops to iterate over arrays in Go is simple and powerful, whether utilizing basic loops, leveraging range, or handling multi-dimensional arrays. The choice of method often depends on specific requirements, such as the need for index values, mutability, and code clarity.