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
Copy an array by value and reference into another array
How to assign and access array element values in Go?
Initialize values for specific array elements in Go
Initializing an Array with ellipses in Go
Golang check if array element exists
What is an Array in Go?
Tricks to filter array elements in Go
Declaring an Integer or String Array of Five Elements in Go
How to initialize an Array with an Array Literal in Go?