Go Arrays
In Go, an array is a special type of variable that contains multiple values. The following string variable, ‘fname’, has been defined and initialised with the name ‘Bob’.
var fname string = "Bob"
If multiple names need to be stored, instead of having a different variable for each, an array could be used.
var fname = [4]string{} fname[0] = "Bob" fname[1] = "George" fname[2] = "Fred" fname[3] = "Alan"
The first line above declares an empty array of type 'string', that can contain four elements. Each element in an array has an index number, which is used in lines two to five above to populate the four elements. Array elements can also be updated in this fashion. Notice that the first index number is a zero and not a one.
The declaration and initialisation of an array can be shortened by combining into one statement.
var fname = [4]string{"Bob", "George", "Fred", "Alan"}
As with ordinary variables, the 'var' keyword can be omitted.
fname := [4]string{"Bob", "George", "Fred", "Alan"}
Where the array is being declared and initialised using either of the above combined methods, the size can be inferred by the number of values being added and replaced with '...'.
fname := [...]string{"Bob", "George", "Fred", "Alan"}
It should be noted that as the size either has to be explicitly specified or is inferred by the number of values added when initialised, the size is fixed from that point on.
As well as being able to use the index number to populate a particular element in an array, it can also be used to extract the value of an element in an array, in order to carry out a particular task, or simply just to display it.
fmt.Println(fname[2])
Here, the element with an index number of two would be displayed, in this case “Fred”.
In order to display all of the elements in an array a 'for-each range' version of a ‘for’ loop can be used.
for i, j := range fname { fmt.Println(i, ": ", string(j)) }
With each iteration through the loop, the index number of the element is placed in the variable 'i', whilst the actual value is placed in the variable 'j'. This example produces the following output.
0 : Bob 1 : George 2 : Fred 3 : Alan
Finally, if it is necessary to find the length, or number of elements, in an array, this can be achieved using the 'len' command.
fmt.Println(len(fname))