Understanding Arrays in Go Programming

Arrays in Go represent fixed-length sequences of elements with the same type. Each element in an array is accessible by its index, and the total number of elements defines the array's length.

Array Declaration Syntax

Go provides several ways to declare arrays:

var byteArray [32]byte            // 32-element byte array
var pointArray [1000]*float64     // Array of float pointers
var matrix [3][5]int              // 2D integer array
var cube [2][2][2]float64         // 3D float array

Array lengths are fixed at declaration time and can be queried using the len() function:

var names [5]string
length := len(names)  // Returns 5

Accessing Array Elements

Array indices start at 0. Elements can be accessed using traditional loops or the range keyword:

// Traditional loop
for i := 0; i < len(data); i++ {
    fmt.Printf("Index %d: %v\n", i, data[i])
}

// Range-based iteration
for idx, val := range data {
    fmt.Printf("Index %d: %v\n", idx, val)
}

The range keyword returns both the index and value for each element.

Value Semantics

Arrays in Go are value types. When passed to functions or assigned to new variables, a complete copy is created:

func updateArray(arr [5]int) {
    arr[0] = 100
    fmt.Println("Inside function:", arr)
}

func main() {
    original := [5]int{1, 2, 3, 4, 5}
    updateArray(original)
    fmt.Println("Original array:", original) // Unchanged
}

This behavior means function parameters receive copies rather than references to the original array.

Tags: Go programming Arrays Data Structures

Posted on Thu, 07 May 2026 05:03:49 +0000 by fluteflute