Arrays in Go

Arrays in Go

In this tutorial, we are going to discuss arrays in Go language. Similar to any other programming language, the go language also has an array data structure. But in go, arrays behave a little differently from other languages and have something called slice in go language, which is like a reference to an array. In this article, we will study only the array.

Arrays in Go

An array is an indexed collection of a fixed number of homogeneous data elements that belong to the same type.

The main advantage of the array is we can represent multiple values under the same name. So that readability of the code will be improved.

But the main disadvantage of the array is fixed in size. i.e., once we created the array with some size, there is no chance of increasing or decreasing the size based on our requirement.

Mixing values of different types, such as an array containing both strings and integers, is not allowed in the Go language.

Array Declaration

An array belongs to type [n]T. n denotes the number of elements in an array, and T represents the type of each element. The number of elements n is also a part of the type (We will discuss this in more detail shortly.)

package main

import (
    "fmt"
)

func main() {
    var a [10]int //int array with length 10
    fmt.Println(a)
}

Output

[0 0 0 0 0 0 0 0 0 0]

Run in playground

In the above example, var a [10]int declares an integer array of length 10. All elements in an array are automatically assigned the zero value of the array type.

In this case, a is an integer array, and hence all elements of a are assigned to 0, the zero value of int.

Please note that the index of an array starts from 0 and ends at length – 1. Let’s assign some values to the above array.

package main

import (
    "fmt"
)

func main() {
    var a [10]int //int array with length 10
    a[0] = 10 // array index starts at 0
    a[1] = 20
    a[2] = 30
    a[3] = 40
    a[4] = 50
    fmt.Println(a)
}

Output

[10 20 30 40 50 0 0 0 0 0]

Run in playground

It is not necessary that all elements in an array have to be assigned a value during a shorthand declaration. Let’s create the same array using the shorthand declaration.

package main 

import (  
    "fmt"
)

func main() {  
    a := [10]int{10, 20, 30, 40, 50} // short hand declaration to create array
    fmt.Println(a)
}

Output

[10 20 30 40 50 0 0 0 0 0]

Run in playground

In the above example inline no. 8 a := [10]int{10, 20, 30, 40, 50} declares an array of length 10 but is provided with only 5 values 10 20 30 40 50. The remaining 5 elements are assigned 0 automatically.

In Go language, we can even ignore the array’s length in the declaration and replace it with … and let the compiler find the length for us. This is done in the following program.

package main

import (
    "fmt"
)
func main() {
    a := […]int{10, 20, 30} // … makes the compiler determine the length
    fmt.Println(a)
}

Output

[10 20 30]

Run in playground

The size of the array is a part of the type. Hence [10]int and [20]int are distinct types. Because of this, arrays cannot be resized.

package main

func main() {  
    a := [5]int{10, 20, 30}
    var b [10]int
    b = a //not possible since [5]int and [10]int are distinct types
}

Output

./prog.go:6:7: cannot use a (type [5]int) as type [10]int in assignment

Run in playground

Arrays are value types

Arrays in Go are value types and not reference types. This means that when they are assigned to a new variable, a copy of the original array is assigned to the new variable.

If changes are made to the new variable, it will not be reflected in the original array.

package main

import "fmt"

func main() {
	a := [...]string{"C", "C++", "Java", "Python", "PHP"}
	b := a // a copy of a is assigned to b
	b[1] = "Golang"
	fmt.Println("a is ", a)
	fmt.Println("b is ", b)
}
a is  [C C++ Java Python PHP]
b is  [C Golang Java Python PHP]

Run in playground

Similarly, when arrays are passed to functions as parameters, they are passed by value, and the original array is unchanged.

package main

import "fmt"

func myfunction(num [3]int) {  
    num[0] = 40
    fmt.Println("Inside function ", num)

}
func main() {  
    num := [...]int{10, 20, 30}
    fmt.Println("Before passing to function ", num)
    myfunction(num) //num is passed by value
    fmt.Println("After passing to function ", num)
}

Output

Before passing to function  [10 20 30]
Inside function  [40 20 30] 
After passing to function  [10 20 30]

Run in playground

Length of an array

The length of the array is found by passing the array as a parameter to the len function.

package main

import "fmt"

func main() {
	a := [...]int{10, 20, 30, 40}
	fmt.Println("length of a is", len(a))
}

Output

length of a is 4

Run in playground

Iterating arrays using range

The for loop can be used to iterate over elements of an array.

package main

import "fmt"

func main() {
	a := [...]int{10, 20, 30, 40}
	for i := 0; i < len(a); i++ {
		fmt.Printf("%d element of a is %d \n", i, a[i])
	}
}

Output

0 element of a is 10  
1 element of a is 20  
2 element of a is 30  
3 element of a is 40  

Run in playground

Go language provides a better and concise way to iterate over an array by using the range form of the for loop. range returns both the index and the value at that index.

package main

import "fmt"

func main() {  
    a := [...]int{10, 20, 30, 40}
    sum := int(0)
    for index, value := range a {//range returns both the index and value
        fmt.Printf("%d element of a is %d\n", index, value)
        sum += value
    }
    fmt.Println("\nsum of all elements of a",sum)
}

Output

0 element of a is 10 
1 element of a is 20 
2 element of a is 30 
3 element of a is 40 

sum of all elements of a 100

In case you want only the value and want to ignore the index, you can do this by replacing the index with the _ blank identifier.

for _, v := range a { 
   //ignores index   
}

The above for loop ignores the index. Similarly the value can also be ignored.

Multidimensional arrays

The arrays we created so far are all single dimension. It is possible to create multidimensional arrays.

package main

import "fmt"

func printarray(a [3][2]string) {  
    for _ , v1 := range a {
        for _ , v2 := range v1 {
            fmt.Printf("%s ", v2)
        }
        fmt.Println()
    }
}

func main() {  
    a := [3][2]string{
        {"Lion", "Tiger"},
        {"Dog", "Cat"},
        {"Pigeon", "Parrot"}, //this comma is necessary. The compiler will complain if you omit this comma
    }
    printarray(a)
    var b [3][2]string
    b[0][0] = "Apple"
    b[0][1] = "OnePlus"
    b[1][0] = "Facebook"
    b[1][1] = "Quora"
    b[2][0] = "Dell"
    b[2][1] = "Macbook"
    fmt.Println()
    printarray(b)
 }

Output

Lion Tiger  
Dog Cat  
Pigeon Parrot  

Apple OnePlus  
Facebook Quora  
Dell Macbook

Run in playground

In the above program, a two-dimensional string array a has been declared using shorthand syntax. The comma at the end of the line is necessary. This is because the lexer automatically inserts semicolons according to simple rules.

Please read here if you are interested to know more as to why this is needed.

Another 2d array b is declared, and strings are added to it one by one for each index. This is another way of initializing a 2d array.

Arrays in Go
Scroll to top