mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Go - Arrays

  • An array is a numbered sequence of elements of a single type
  • The array’s length is part of its type (e.g. [10]int)
  • Arrays have a fixed size and cannot be resized

Declaration

go
var numbers [10]int  // Array of 10 integers

var names [5]string  // Array of 5 strings

var matrix [3][3]int // Multidimentional array of integers (3x3)

Zero Value

The zero value of an array is an array with all the elements initialized to the zero value of their type.

go
var numbers [4]int   // [0 0 0 0]

var names [3]string  // ["" "" ""]

var booleans [4]bool // [false false false false]

Initialization

go
// Array literal.
a := [6]int{1, 2, 3, 4, 5, 6} // [6]int

// If not all the elements are provided in the literal
// the missing elements are set to the zero value for the array element type.
n := [4]int{1, 2} // [4]int{1, 2, 0, 0}

Size Inference

The compiler can infer the size of the array based on the number of elements provided when using the ... notation:

go
n := [...]int{1, 2, 3, 4, 5, 6} // [6]int

Length

The len() function may be used to get the length of an array:

go
length := len(n) // 6

Array Elements

The array elements can be accessed using their index in square brackets []:

go
first := array[0]           // Access the 1st element

last := array[len(array)-1] // Access the last element

n := matrix[0][2]           // Access the 3rd element of the 1st array

array[1] = 10               // Set the value of the 2nd element

matrix[1][0] = 7            // Set the value of the 1st element of the 2nd array

// A panic will occur at runtime if the index is out of range.
array[100] // panic: runtime error: index out of range

// Pointer to an array.
p := &array

// Explicit pointer dereferencing is not required.
p[0] = 10

// Shorthand for
(*p)[0] = 10