Sling Academy
Home/Golang/Using Loops to Iterate Over Arrays in Go

Using Loops to Iterate Over Arrays in Go

Last updated: November 23, 2024

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.

Next Article: Passing Arrays to Functions: Go's Value Semantics Explained

Previous Article: Exploring Multidimensional Arrays in Go

Series: Working with Arrays in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant