Golang Working with Arrays

Golang Working with Arrays

  • Arrays in go language are fixed sized collection of homogeneous elements.
  • Array elements are stored sequentially and can be accessed using index.

Golang Array declaration

We can declare the arrays in go as follows

var nameOfArray [size] Type

Golang int Array declaration

var numbers[5] int

Golang string Array declaration

var names[5] string

In the same way we can declare arrays for any type like float32, struct, etc.

Golang Array initializing and accessing the elements

We can access the golang array elements with indexes. See the below image to understand it in a better way.

Golang array indexes

Note: Array indexes always starts with 0

package main

import "fmt"

func main(){
    var numbers[5] int

    fmt.Println("numbers = ", numbers);

    // assign element to array
    numbers[0] = 100
    numbers[4] = 500
    fmt.Println("numbers = ", numbers);

}

Output:

numbers =  [0 0 0 0 0]
numbers =  [100 0 0 0 500]

In the above code, we initialized the array of size 5 and type int. For integer data type we have the default value 0. We updated the value of the array at index zero to value 100 with statement numbers[0] = 100 and did the same for index 4.

Golang iterating the array elements using range.

Let's write a simple program to print the names in an array.

package main
import "fmt"

func main(){
    names := [] string {"Anji", "Ram", "John", "Shera"}

    for index, name := range names {
        fmt.Println("index = ", index, "name = ", name)
    }
}

Output:

index =  0 name =  Anji
index =  1 name =  Ram
index =  2 name =  John
index =  3 name =  Shera

We can also declare the array with the known elements like above. We can use the range keyword with go array and for loop.

Golang Multidimensional arrays

Let's define a 3X3 matrix with the elements

package main
import "fmt"

func main(){
    matrix := [3][3]int{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
    }
    fmt.Println("matrix = ", matrix)

    // update the element
    matrix[1][1] = 100
    fmt.Println("matrix = ", matrix)
}

Ouput:

matrix =  [[1 2 3] [4 5 6] [7 8 9]]
matrix =  [[1 2 3] [4 100 6] [7 8 9]]