0
0
GoHow-ToBeginner · 3 min read

How to Iterate Over Array in Go: Simple Syntax and Examples

In Go, you can iterate over an array using a for loop with an index or a for range loop that gives both index and value. The for range loop is the most common and readable way to access each element in the array.
📐

Syntax

There are two main ways to loop over an array in Go:

  • Using a classic for loop: You use an index to access each element.
  • Using a for range loop: This gives you both the index and the value directly.

This makes it easy to read and write loops over arrays.

go
var arr = [3]int{10, 20, 30}

// Classic for loop
for i := 0; i < len(arr); i++ {
    // i is index, arr[i] is value
}

// For range loop
for i, v := range arr {
    // i is index, v is value
}
💻

Example

This example shows how to print each element of an array using a for range loop.

go
package main

import "fmt"

func main() {
    arr := [4]string{"apple", "banana", "cherry", "date"}

    for i, fruit := range arr {
        fmt.Printf("Element at index %d is %s\n", i, fruit)
    }
}
Output
Element at index 0 is apple Element at index 1 is banana Element at index 2 is cherry Element at index 3 is date
⚠️

Common Pitfalls

One common mistake is modifying the loop variable instead of the array element. The range loop copies the value, so changing it won't affect the array.

Also, forgetting to use the index when needed or ignoring the value can cause confusion.

go
package main

import "fmt"

func main() {
    arr := [3]int{1, 2, 3}

    // Wrong: modifying loop variable does not change array
    for _, v := range arr {
        v = v * 2 // This changes only v, not arr
    }
    fmt.Println("After wrong loop:", arr)

    // Right: modify array using index
    for i := range arr {
        arr[i] = arr[i] * 2
    }
    fmt.Println("After correct loop:", arr)
}
Output
After wrong loop: [1 2 3] After correct loop: [2 4 6]
📊

Quick Reference

Remember these tips when iterating over arrays in Go:

  • Use for range for clean and readable loops.
  • Use the index if you need to modify the array elements.
  • Loop variables in range are copies, not references.

Key Takeaways

Use a for range loop to easily access index and value when iterating over arrays in Go.
Classic for loops with an index are useful when you need to modify array elements.
Loop variables in for range are copies; modifying them does not change the original array.
Always use the index to update array elements inside loops.
For simple reading of array elements, for range loops are the most readable and idiomatic.