Arrays

Arrays are useful when planning the detailed layout of memory and sometimes can help avoid allocation, but primarily they are a building block for slices.

The in-memory representation of [4]int is four integer values laid out sequentially.

image.png

Arrays do not need to be initialised explicitly; the zero value of an array is a ready-to-use array whose elements are themselves zeroed.

Size is part of its type

The types [10]int and [20]int are distinct.

Arrays are Values

An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C). Assign or pass around an array value you will make a copy. To avoid the copy you could pass a pointer to the array, but then that’s a pointer to an array, not an array. One way to think about arrays is as a sort of struct but with indexed rather than named fields: a fixed-size composite value.

array := [...]int{1, 2, 3} 
assignedArray := array

fmt.Println(assignedArray) // [1 2 3]
fmt.Println(&array == &assignedArray) // false
var array = [...]int{1, 2, 3}

func fn(arrayCopy [3]int) {
	fmt.Println(arrayCopy) // [1 2 3]
	fmt.Println(&array == &arrayCopy) // false
}

Pointer arithmetic like C

If you want C-like behaviour and efficiency, pass a pointer to the array, but this style isn't idiomatic Go.

func Sum(a *[3]float64) (sum float64) {
    for _, v := range *a {
        sum += v
    }
    return
}

array := [...]float64{7.0, 8.5, 9.1}
x := Sum(&array)

When to use Arrays?

var daysOfWeek = [7]string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
const width, height = 100, 100
const numPixels = width * height

// Create a array for a fixed-size image buffer
var imageBuffer [numPixels]int

// Simulate filling the buffer with pixel values
rand.Seed(time.Now().UnixNano())
for i := 0; i < len(imageBuffer); i++ {
    imageBuffer[i] = rand.Intn(256) // Random pixel value between 0 and 255
}

// Process the image buffer (example: calculate the average pixel value)
total := 0
for _, pixelValue := range imageBuffer {
    total += pixelValue
}
averagePixelValue := total / numPixels

fmt.Printf("Average Pixel Value: %d\\n", averagePixelValue)

Slice Headers