[Golang (Go) Tutorial] Arrays

Arrays

An array holds a specific number of elements, and it cannot grow or shrink. Different data types can be handled as elements in arrays such as Int, String, Boolean, and others.

An array is a fixed-length sequence of zero or more elements of a particular type. Because of their fixed length, arrays are rarely used directly in Go. Slices, which can grow and shrink, are much more versatile.

Declaring an Array

To declare an array you need to specify the number of elements it holds in square brackets ([]), followed by the type of elements the array holds.

An array is created using the var keyword of a particular type with name, size, and elements.

Syntax:

1
2
3
var array_name[length]Type
or
var array_name[length]Typle{item1, item2, item3, ...itemN}

Example:

1
2
var intArray [5]int
var strArray [5]string

Initializing an Array with an Array Literal

Arrays can also declare using shorthand declaration. It is more flexible than the above declaration.

Syntax:

1
array_name:= [length]Type{item1, item2, item3,...itemN}

Example:

1
2
3
4
5
6
7
// Shorthand declaration of array
x := [5]int{10, 20, 30, 40, 50} // Intialized with values
// [10 20 30 40 50]

// Using var keyword
var y [5]int = [5]int{10, 20, 30} // Partial assignment
// [10 20 30 0 0]

Initializing an Array with new keyword

Arrays can also declare and initialize using new keyword. It will get the point to array.

Syntax:

1
array_name:= new([length]Type)

Example:

1
2
3
var a = new([5]int)
fmt.Printf("%T\n", a) // *[5]int
fmt.Printf("%d\n", a[0]) // 0

Assign and Access Values

You access or assign the array elements by referring to the index number. The index is specified in square brackets. The index of the first element of any dimension of an array is 0, the index of the second element of any array dimension is 1, and so on.

1
2
3
4
5
6
7
8
9
10
11
12
13
var theArray [3]string
theArray[0] = "India" // Assign a value to the first element
theArray[1] = "Canada" // Assign a value to the second element
theArray[2] = "Japan" // Assign a value to the third element

fmt.Println(theArray[0]) // Access the first element value
// India

fmt.Println(theArray[1]) // Access the second element value
// Canada

fmt.Println(theArray[2]) // Access the third element value
// Japan

Get array length

The length of the array is determined with the len function.

In the example, we define an array of strings. We print the number of words in the array.

1
2
3
words := [5]string{ "falcon", "sky", "earth", "cloud", "fox" }

fmt.Println("There are", len(words), "words in the array") // There are 5 words in the array

Initializing an Array with ellipses…

When we use ... instead of specifying the length. The compiler can identify the length of an array, based on the elements specified in the array declaration.

1
2
3
x := [...]int{10, 20, 30}

fmt.Println(len(x)) // 3

Initializing Values for Specific Elements

When an array declare using an array literal, values can be initialize for specific elements.

A value of 10 is assigned to the second element (index 1) and a value of 30 is assigned to the fourth element (index 3).

Example:

1
2
x := [5]int{1: 10, 3: 30}
fmt.Println(x) // [0 10 0 30 0]

Loop Through an Indexed Array

You can loop through an array elements by using a for loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
intArray := [5]int{10, 20, 30, 40, 50}

fmt.Println("\n---------------Example 1--------------------\n")
for i := 0; i < len(intArray); i++ {
fmt.Println(intArray[i])
}

fmt.Println("\n---------------Example 2--------------------\n")
for index, element := range intArray {
fmt.Println(index, "=>", element)

}

fmt.Println("\n---------------Example 3--------------------\n")
for _, value := range intArray {
fmt.Println(value)
}

j := 0
fmt.Println("\n---------------Example 4--------------------\n")
for range intArray {
fmt.Println(intArray[j])
j++
}

Copy Array

Unlike in other languages, array is a value type in Go. This means that when we assign an array to a new variable or pass an array to a function, the entire array is copied.

You can create copy of an array, by assigning an array to a new variable either by value or reference(with &).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
strArray1 := [3]string{"Japan", "Australia", "Germany"}
strArray2 := strArray1 // data is passed by value
strArray3 := &strArray1 // data is passed by refrence

fmt.Printf("strArray1: %v\n", strArray1) // strArray1: [Japan Australia Germany]
fmt.Printf("strArray2: %v\n", strArray2) // strArray2: [Japan Australia Germany]

strArray1[0] = "Canada"

fmt.Printf("strArray1: %v\n", strArray1) // strArray1: [Canada Australia Germany]
fmt.Printf("strArray2: %v\n", strArray2) // strArray2: [Japan Australia Germany]
fmt.Printf("*strArray3: %v\n", *strArray3) // *strArray3: [Canada Australia Germany]

passValue(strArray1)
passReference(strArray3)

fmt.Printf("strArray1: %v\n", strArray1) // strArray1: [Canada Australia Germany]
fmt.Printf("strArray2: %v\n", strArray2) // strArray2: [Japan Australia Germany]
fmt.Printf("*strArray3: %v\n", *strArray3) // *strArray3: [London Australia Germany]

func passValue(strArray [3]string) {
strArray1[0] = "London"
}

func passReference(strArray *[3]string) {
strArray1[0] = "London"
}

Check if Element Exists

To determine if a specific element exist in an array, we need to iterate each array element using for loop and check using if condition.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func main() {
strArray := [5]string{"India", "Canada", "Japan", "Germany", "Italy"}
fmt.Println(itemExists(strArray, "Canada")) // true
fmt.Println(itemExists(strArray, "Africa")) // false
}

func itemExists(arrayType interface{}, item interface{}) bool {
arr := reflect.ValueOf(arrayType)

if arr.Kind() != reflect.Array {
panic("Invalid data-type")
}

for i := 0; i < arr.Len(); i++ {
if arr.Index(i).Interface() == item {
return true
}
}

return false
}

Filter Array Elements

You can filter array element using : as shown below

A value of 10 is assigned to the second element (index 1) and a value of 30 is assigned to the fourth element (index 3).

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
countries := [...]string{"India", "Canada", "Japan", "Germany", "Italy"}

fmt.Printf("Countries: %v\n", countries) // Countries: [India Canada Japan Germany Italy]

fmt.Printf(":2 %v\n", countries[:2]) // :2 [India Canada]

fmt.Printf("1:3 %v\n", countries[1:3]) // 1:3 [Canada Japan]

fmt.Printf("2: %v\n", countries[2:]) // 2: [Japan Germany Italy]

fmt.Printf("2:5 %v\n", countries[2:5]) // 2:5 [Japan Germany Italy]

fmt.Printf("0:3 %v\n", countries[0:3]) // 0:3 [India Canada Japan]

fmt.Printf("Last element: %v\n", countries[len(countries)-1]) // Last element: Italy

fmt.Printf("All elements: %v\n", countries[0:len(countries)]) // All elements: [India Canada Japan Germany Italy]
fmt.Println(countries[:]) // [India Canada Japan Germany Italy]
fmt.Println(countries[0:]) // [India Canada Japan Germany Italy]
fmt.Println(countries[0:len(countries)]) // [India Canada Japan Germany Italy]

fmt.Printf("Last two elements: %v\n", countries[len(countries)-2:len(countries)]) // Last two elements: [Germany Italy]

multidimensional arrays

We can create multidimensional arrays in Go. We need additional pairs of square and curly brackets for additional array dimension.

1
Array_name[Length1][Length2]..[LengthN]Type

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
a := [2][2]int{

{1, 2},
{3, 4}, // the trailing comma is mandatory
}

fmt.Println(a)

var b [2][2]int

rand.Seed(time.Now().UnixNano())

for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
b[i][j] = rand.Intn(10)
}
}

fmt.Println(b)

Compare two arrays

If an array’s element type is comparable then the array type is comparable too, so we may directly compare two arrays of that type using the == operator, which reports whether all corresponding elements are equal. The != operator is its negation.

1
2
3
4
5
6
a := [2]int{1, 2}
b := [...]int{1, 2}
c := [2]int{1, 3}
fmt.Println(a == b, a == c, b == c) // "true false false"
d := [3]int{1, 2}
fmt.Println(a == d) // compile error: cannot compare [2]int == [3]int

References

[1] Arrays in Go - GeeksforGeeks - https://www.geeksforgeeks.org/arrays-in-go/

[2] Arrays in Go with examples - golangprograms.com - https://www.golangprograms.com/go-language/arrays.html

[3] Go array - working with arrays in Golang - https://zetcode.com/golang/array/