Go Gopher How to Go

Arrays in Go are fixed-size collections of elements of the same type. They are useful for storing a known number of items. The table below contains information on patterns, characteristics, operations and more!

💡 Key Points

  • Array size is fixed and part of its type: [3]int and [4]int are different types
  • Arrays are value types - assignment and function parameters create copies
  • Use [...] to let compiler infer size from initialization
  • Zero value of array elements depends on the element type
  • Slices are almost always preferred over arrays for flexibility
  • Arrays are useful for fixed-size buffers or when you need value semantics

Declaring and Using an Array

package main
import "fmt"
func main() {
  // Declare an array of integers with a size of 5
  var numbers [5]int

  // Initialize the array with values
  numbers[0] = 10
  numbers[1] = 20
  numbers[2] = 30
  numbers[3] = 40
  numbers[4] = 50

  // Print the array
  fmt.Println("Array:", numbers)

  // Access individual elements
  fmt.Println("First element:", numbers[0])
  fmt.Println("Second element:", numbers[1])

  // Get the length of the array
  fmt.Println("Length of array:", len(numbers))
}
Output:
Array: [10 20 30 40 50]
First element: 10
Second element: 20
Length of array: 5

Array Declaration Patterns

PatternExampleDescription
var name [size]typevar a [5]intDeclare array with zero values
[size]type{values}[3]int{1, 2, 3}Declare and initialize with values
[...]type{values}[...]int{1, 2, 3, 4}Size inferred from values
[size]type{index: value}[5]int{2: 10, 4: 20}Initialize specific indices
[size][size]type[3][2]int{{1,2},{3,4},{5,6}}Multi-dimensional arrays

Array Operations

OperationSyntaxExampleDescription
Access elementarray[index]a[0]Get or set element at index
Get lengthlen(array)len(a)Returns the number of elements
Iteratefor i, v := range arrayfor i, v := range aLoop through index and value
Comparearray1 == array2a == bArrays of same type/size are comparable
Copyb := ab := aCreates a copy (value type)
Pass to functionfunc(arr [5]int)process(a)Passed by value (copied)

Array vs Slice

FeatureArraySlice
SizeFixed at compile timeDynamic, can grow/shrink
Declaration[5]int[]int
MemoryValue type (copied)Reference type (points to array)
Type identitySize is part of typeSize not part of type
Use caseKnown, fixed number of elementsVariable number of elements
PerformanceStack allocated, predictableHeap allocated, flexible