Arrays and Structs
Learn about basic collections in Go.
We'll cover the following...
Arrays
Arrays are similar to variables in that they store values, but they store multiple values. Rather than declaring various variables, we can group them into a single array. Each individual variable in the group is an element, and can be accessed via its position in the group. The first element of an array can be found at position 0
.
Declaring an array
We can declare an array using the var
keyword or the :=
operator. The length of an array can be defined (known) or inferred (unknown). The respective syntax is shown below:
- If it has a defined length:
var name = [length]datatype{values}
- If it has an inferred length (denoted by the
[...]
symbol), it means the length is been generated by the compiler, after counting the number of values present in the array:
var name = [...]datatype{values}
package mainimport ("fmt")func main() {var nums = [3]int{1,3,7} //defined lengthcountries := [...]string{"Nigeria", "Netherlands", "Norway"} //inferred lengthfmt.Println(nums)fmt.Println(countries)}
Accessing an array
We can get a specific array value by using the index number. We can also use the index number to access the value and change it.
package mainimport ("fmt")func main() {countries := [...]string{"Nigeria", "Netherlands", "Norway","Rwanda"}fmt.Println("Printing the values at different indexes")fmt.Println(countries[0])fmt.Println(countries[1])fmt.Println(countries[2])fmt.Println(countries[3])fmt.Println("Updating the value of the element at index 3")countries[3] = "Spain"fmt.Println(countries[3])}
Here’s a breakdown of what's happening in the example above:
Line 5: We declare an array named
countries
with a fixed length (determined by the number of elements in the initializer list) and string elements.Lines 7–9: We print the values at different indexes of the
countries
array.Line 12: We update the value of the element at index 3 in the
countries
array.Line 13: Here we print the updated value at index 3.
Initializing elements
If we don’t initialize an array or one of its given values in our code, it takes on the default value of its type. The int
has a default value of 0
, and string
has a default value of ""
. It’s also possible to initialize only specific elements within the array, as demonstrated in the following code. We can find the length of an array using the len()
method.
package mainimport ("fmt")func main() {var nums := [3]int{3,7} //partial initializationtest := [...]int{3:77,7:49} //initializing only some elementsfmt.Println(nums)fmt.Println(test)fmt.Println(len(nums))fmt.Println(len(test))}
Here’s a breakdown of what's happening in the example above:
Line 5: We declare an array named
nums
with a fixed length of 3 and initializes the first two elements with values 3 and 7, respectively. The third element is automatically initialized with the zero value for the element type (which isint
in this case).Line 6: We declare an array named
test
without explicitly specifying the length. The length is inferred from the number of initializers provided. In this case, the array has a length of 8, and elements at indexes 3 and 7 are initialized with values 77 and 49, respectively. The other elements are automatically initialized with the zero value for the element type (int
).Line 7: We print the
nums
array.Line 8: We print the
test
array.Line 10: We print the length of the
nums
array.Line 11: We print the length of the
test
array.
Checking the existence of an element
In Go, we can check if a specific element exists in an indexed array by looping through the array and comparing each element. This can be done using a simple for
loop and an if
statement. By iterating through the array and comparing the desired element with each element in the loop, we can determine whether the element exists in the array or not. Let’s run the following code demonstrating how to check if an element exists in an array:
package mainimport ("fmt""reflect")func main() {sports := [...]string{"football", "basketball", "hockey"}fmt.Println("Looping through the array")for i := 0; i < len(sports); i++ {fmt.Println(sports[i])}fmt.Println("The sport football exist? (true or false)")//Searching for a particular itemfmt.Println(itemExists(sports, "football"))}func itemExists(arrayType interface{}, item interface{}) bool {arr := reflect.ValueOf(arrayType)if arr.Kind() != reflect.Array {panic("Invalid datatype")}for i := 0; i < arr.Len(); i++ {if arr.Index(i).Interface() == item {return true}}return false}
In the example above, the code defines an array of strings called sports
and prints each element of the array using a for
loop. It also includes a function named itemExists
that checks if a given item exists in an array by iterating over the array and comparing each element with the item using reflection. The main function calls itemExists
to check if “football” exists in the sports
array and prints the result.
An interface
can be a type or a group of methods. Any sort of value, including values of custom types, can be stored in a variable of an interface
...