Golang arrays

Arrays

Array is a data structure used to store a sequence of elements of same type in a fixed-size. An array is stored in the memory in a contiguous block of memory and its elements are accessed by an index.

Rarely arrays are used in Go, we have other option in place of an array. All elements in an array must be of the same type of your declaration.

Different ways to declare an array

We can declare an array in some different ways.

It declares x as an array of 3 int elements:

var x = [3]int{}

If you try to print this array, you’ll see all positions have the zero value of its type.

>> [0 0 0]

We can declare the array and set it’s elemnts at same time:

var x = [3]int{1, 2, 3}
>> [1 2 3]

Using an array literal:

var x = [...]int{1, 2, 3}
>> [1 2 3]

Setting values at specific positions

var x = [...]int{1, 3:1, 7, 8, 9}
>> [1 0 0 1 7 8 9]

Getting the size of an array

var x = [5]int{1, 2, 3, 4, 5}
length := len(x)
fmt.Println(length)
>> 5

Reading a position inside an array

var x = [5]int{1, 2, 3, 4, 5}
a := x[1]
fmt.Println(a)
>> 2

Writing in a position of an array

var x = [...]int{7, 8, 9}
x[0] = 1
fmt.Println(x)
>> [1 8 9]

Iterating over an array

var x = [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
for i, v := range x {
    fmt.Printf("Index: %d - Value: %d\n", i, v)
}
>> Index: 0 - Value: 1
>> Index: 1 - Value: 2
>> Index: 2 - Value: 3
>> Index: 3 - Value: 4
>> Index: 4 - Value: 5
>> Index: 5 - Value: 6
>> Index: 6 - Value: 7
>> Index: 7 - Value: 8
>> Index: 8 - Value: 9
>> Index: 9 - Value: 10

Getting a slice from an array

You can get just a part of the array using this syntax myArray[start:end], the start is inclusive and the end is exclusive

var x = [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
a := x[1:5]
fmt.Println(a)
>> [2 3 4 5]