In this tutorial, we will be checking out the Go array data type which falls under the aggregate data type of composite typed. As we discussed in the previous tutorial Go comes with some primitive basic data types: int, float, complex numbers, Boolean, and string. Here we check what is the aggregate data type and its classification further about the declaration and syntax of its classifications such as arrays and struct.
Arrays in Golang are data structures with the same type of elements with fixed lengths. In array data type you have to define the size when you initialize or declare them. They can have zero or more elements.
Disadvantage: The size of the array can’t be resized once it is created. Therefore, arrays aren't commonly used in Go programs, but they form the foundation for slices and maps.
Advantage: In struct type, you can store more than one value of various basic data types like int, float, a string to treat them as a single entity.
To declare a variable in Golang as of array type follows the below syntax:
var <variable name> <size of array><data type>
Example
var a[4]int
A variable “a” is declared using the var keyword which can hold integer type values of array size 4. ie the variable “a” can hold 4 elements of numeric values. The variable can be of any data type like string, float, etc.
<variable name> := <size of array>.<data type{<value1><value2>.....}
Example
colors := [3]string{"blue", "orange", "yellow"}
A variable “colors” of string type which holds 3 elements such as blue, orange, yellow colors are declared.
In arrays, elements are assigned or accessed by indicating the index number corresponding to each array element. The square brackets [ ] specify the corresponding array index. Example A [1], A [5].
Let’s understand with simple Go programs the above defines syntax:
package main
import "fmt"
func main() {
var a [4]int //Declare array
a[1] = 1 //initialize array values
a[3]= 3
fmt.Println(a[0]) //print statement displays variable values
fmt.Println(a[1])
fmt.Println(a[2])
fmt.Println(a[3])
}
Output:
0 1 0 3
Explanation :
import "fmt"
func main() {
//Declare a array
//colors[0] =”blue”
//colors[1] =”orange”
//colors[2] =”yellow
colors := [3]string{"blue", "orange", "yellow"} //shorthand array declaration
print(colors)
}
func print(colors [3]string) { //Pass array as a function argument
fmt.Println(colors)}
Output:
[blue orange yellow]
Ellipsis is another way of declaring and initializing an array when the exact number of data is known but positions are unknown. An ellipsis is denoted by (...) as shown in the below example
s := [...]int{4, 5, 6}
Let's modify the program we used in the previous section to use an ellipsis. The code should look like this example:
package main
import "fmt"
func main() {
//Declare a array
//colors[0] =”blue”
//colors[1] =”orange”
//colors[2] =”yellow
colors := [...]string{"blue", "orange", "yellow"} //ellipsis array declaration
print(colors)
}
Output:
[blue orange yellow]
An array allows the initialization of specific values to its contained elements during the declaration of an array.
An array A is declared using shorthand declaration, the size of the array is 6. Three values are specified to certain array elements. A value 50 is assigned to the second element (index 1), A value 30 is assigned to the fourth element (index 3), A value 30 is assigned to the sixth element (index 5)
Example
package main
import "fmt"
func main() {
//initializing values to specific array elements
A := [6]int{1: 50, 3: 30,5:50}
fmt.Println("Initializing values to specific array elements \n",A)
fmt.Println("Default type of unspecified elements is 0 \n")
}
Output:
Initializing values to specific array elements [0 50 0 30 0 50] Default type of unspecified elements is 0
NOTE: If a value is not specified default value for integer type is zero, and for string a space “”.
Golang support one-dimensional (1-D) arrays as well as multidimensional arrays.
Multi-dimensional arrays in Golang support working with complex data structures.
You can create a multi-dimensional array using the following syntax:
Syntax:
var <variable_name>[size 1][size 2]….[size m]<type>
Example
var twoDM [3][5]int //Two dimensional array
var threeDM [4][2][3]int //Three dimensional array
The keyword var followed by a variable name like twoDM(2D) mentions that it is a 3 *5 matrix type with 3 rows and 5 columns. Similarly, the three-dimensional array is also declared.
package main
import "fmt"
func main() {
var twoD [3][2]int
for i := 0; i < 3; i++ {
for j := 0; j < 2; j++ {
twoD[i][j] = (i + 1) * (j + 1)
}
fmt.Println("Row", i, twoD[i])
}
fmt.Println("\nExample of multi dimensional :", twoD)
}
Output:
Row 0 [1 2] Row 1 [2 4] Row 2 [3 6] Example of multi dimensional : [[1 2][2 4][3 6]]
There are two types:
a = [3][2]int{
{1,2} , /* initialize a[0] row indexed by 0 */
{2,4} , /* initializer a[1] row indexed by 1 */
{3,6} /* initializer a[2] row indexed by 2 */
}
var a = [3][2]int{ {0,0}, {8,2}, {2,4}, {3,9},{4,7}}
In Golang the length of an array can be identified by using len () function. The len () function returns an integer type mentioning the total number of elements defined in an array.
len (variable name)
colors := [4]string{"blue ","black","white","orange"} length := len(colors)
The above-given code shows the declaration of colors as an array of size 4 with 4 different colors. The function len (variable name) returns a value 4 here variable name is color so call function len(colors)
Example
package main
import "fmt"
func main() {
// Create an exmaple array
array := []int{1, 2, 3, 4, 5}
//create array with var keyword of string type & assign values
var array1 [3]string
array1[0] ="Go"
array1[1] ="Lang"
// Print number of items
fmt.Println("First array ",array)
fmt.Println("Array Length:", len(array))
fmt.Println("Second array ",array1)
fmt.Println("Length of array1 :", len(array1))
// Add an item and print again
array = append(array, 6)
fmt.Println(" Length after apppending element to array :", len(array))
}
Output:
First array [1 2 3 4 5] Array Length : 5 Second array [Go Lang] Length of array1 : 3 Length after appending element to an array : 6
To determine the existence of a specific element in an array, perform an iteration using for loop followed by an if condition to check elements within an array.
Syntax:
key word itemExists<variable name><item needs to check>
The keyword itemExists
followed by the variable name and the element needs to be checked inside the array for its existence returns either true or false based on its evaluation. If an element exists return True else False.
Example
package main
import (
"fmt"
"reflect"
)
func main() {
//Declare array of type string
Array := [4]string{"Green", "blue", "orange", "yellow"}
fmt.Println(itemExists(Array, "Green")) //item exist returns true
fmt.Println(itemExists(Array, "orange")) //item exist returns true
fmt.Println(itemExists(Array, "white")) //item does not exist returns 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
}
Output:
true true false
Golang supports filtering of arrays, the selection of required elements from the set of elements contained by an array
Syntax
Array elements are filtered using the symbol “: “
Example
package main
import "fmt"
func main() {
colors := [...]string{"green", "orange", "white", "blue", "red"}
fmt.Printf("colors: %v\n", colors)
fmt.Printf(":2 %v\n", colors[:2]) //Return first 2 elements
fmt.Printf("1:3 %v\n",colors[1:3]) // return first 2 elements exclude 3rd element
fmt.Printf("2: %v\n", colors[2:])
}
Output:
colors : [green orange white blue red] : 2 [green orange] 1: 3 [orange white] 2 : [white blue red]
An array can be copied to another array by creating a new variable of array type and assigning values to a new array or passing its reference type.
Example
package main
import "fmt"
func main() {
Array1:= [3]string{"orange", "yellow", "white"}
Array2:= Array1 // elements are passed by value
Array3:= &Array1; // elements are passed by reference
fmt.Printf ("Display Array1: %v\n", Array1) //Display array1
fmt.Printf ("Display Array2: %v\n", Array2) //Display copied elements in Array2
Array1[0] = "green"
fmt.Printf("Display Array1 after appending new value: %v\n", Array1)
fmt.Printf("*Array3: %v\n", *Array3) //Display array 1 element passed by reference
}
Output:
Display Array1: [orange yellow white] Display Array2: [orange yellow white] Display Array1 after appending new value : [green yellow white] *Array3 : [green yellow white]