How to iterate over an Array using for loop?
You can loop through an array elements by using a for loop.
Example
package main
import "fmt"
func main() {
intArray := [5]int{10, 20, 30, 40, 50}
fmt.Println("\n---------------Example 1--------------------\n")
for i := 0; i < len(intArray); i++ {
fmt.Println(intArray[i])
}
fmt.Println("\n---------------Example 2--------------------\n")
for index, element := range intArray {
fmt.Println(index, "=>", element)
}
fmt.Println("\n---------------Example 3--------------------\n")
for _, value := range intArray {
fmt.Println(value)
}
j := 0
fmt.Println("\n---------------Example 4--------------------\n")
for range intArray {
fmt.Println(intArray[j])
j++
}
}
Most Helpful This Week
How to initialize an Array with an Array Literal in Go?
How to assign and access array element values in Go?
Declaring an Integer or String Array of Five Elements in Go
What is an Array in Go?
Copy an array by value and reference into another array
Initialize values for specific array elements in Go