7. Arrays

In Go, an array is a numbered sequence of elements of a specific length.

Arrays are easily understood with the help of this example:

Program: ar1.go


 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6         //exactly 5 ints. The type of elements
 7         //and length are both part of the array's
 8         //type. By default an array is zero-valued,
 9         //and int types are by default initialized 
10         //with a 0 value.
11         var arr [5]int
12         fmt.Println("arr:", arr)
13 
14         //We can set a value at an index using the
15         //array[index] = value syntax, and get a
16         //value with array[index].
17         arr[3] = 10
18         fmt.Println("set:", arr)
19         fmt.Println("get:", arr[3])
20 
21         //The builtin len returns the length of
22         //an array
23         fmt.Println("len:", len(arr))
24 
25         //Use this syntax to declare and initialize
26         //an array in one line.
27         arr2 := [5]int{1, 2, 3, 4, 5}
28         fmt.Println("arr2:", arr2)
29 
30         //multidimensional array
31         arr3 := [2][2] int{ {1,2}, {3,4} }
32         fmt.Println("arr3:", arr3)
33 }

The output is:

arr: [0 0 0 0 0]
set: [0 0 0 10 0]
get: 10
len: 5
arr2: [1 2 3 4 5]
arr3: [[1 2] [3 4]]

Note that you can have the compiler count the array elements for you:

b := [...]string{"Golang", "Challenge"}

In both cases, the type of b is [2]string.

Go’s arrays are values. An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C). This means that when you assign or pass around an array value you will make a copy of its contents. (To avoid the copy you could pass a pointer to the array, but then that’s a pointer to an array.)

The in-memory representation of [4]int is just four integer values laid out sequentially:

Array

Array

Remember:

Array function arguments

If you are a C or C++ developer arrays for you are pointers. When you pass arrays to functions the functions reference the same memory location, so they can update the original data. Arrays in Go are values, so when you pass arrays to functions the functions get a copy of the original array data. This can be a problem if you are trying to update the array data.