## 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. `int`)
• Arrays have a fixed size and cannot be resized

## Declaration

go
``var numbers int  // Array of 10 integersvar names string  // Array of 5 stringsvar matrix 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 int   // [0 0 0 0]var names string  // ["" "" ""]var booleans bool // [false false false false]``

## Initialization

go
``// Array literal.a := int{1, 2, 3, 4, 5, 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 := int{1, 2} // 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} // 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           // Access the 1st elementlast := array[len(array)-1] // Access the last elementn := matrix           // Access the 3rd element of the 1st arrayarray = 10               // Set the value of the 2nd elementmatrix = 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 // panic: runtime error: index out of range// Pointer to an array.p := &array// Explicit pointer dereferencing is not required.p = 10// Shorthand for(*p) = 10``