Go Arrays

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.

What is an array in Go Lang?

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.

GO : Array

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.

How to declare arrays in Go Lang?

To declare a variable in Golang as of array  type follows the below syntax:

  1. Using var keyword:  In Go Programming language, An array is declared using the var keyword of a particular type with name, size, and elements. Values are set to default zero value 
    
    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.

    GO : Array
    •     In Golang, the type of array is one-dimensional.
    •     Array length is fixed and cannot be changed once after it is created.
    •     An array can store duplicate values. A [0] = 50 & A [4] =50
    •     Array elements/values are accessed by index values.
    •     Consider the below shown array with elements 50,60,70,80,50,90.Let’s name the array A with indexes 0,1,2,3,4,5
      GO : Array
  2.  Shorthand declaration:  In Golang, arrays can also be declared using shorthand declaration. It is more flexible than the above declaration. Both sizes & values are specified
    
    <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.

    GO : Array

Assign and Accessing array elements by their index

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:

Program 1: using the var keyword


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 :

  •   Go initializes each element with the default data type.
  •   Variable “a” of array size 4 can hold 4 elements ie a[0],a[1],a[2],a[3] each array have some data contained within it.By default a[0]=0,a[1]=0,.....if no values are initialized. (In array indexing begins with 0)
  •   So In this case, the default value for int is zero. 
  •  Here a[0] =0,a[2]=0
  • Here a[1]=1, a[3]=3 are assigned so it displays values 1 & 3  respectively which means you can assign a value to a specific position.
     

    Program 2: using the shorthand array declaration

    
    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]
    
  • how to declare an array using shorthand variable declaration
  • How to Pass array as a function argument

What is Ellipsis in arrays

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]

Initializing Values for Specific Elements

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 “”.

Multi-Dimensional Array in GO

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.

GO : Array

Program: Declaration of 2D array


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]]

Initializing Multi-Dimensional Arrays

There are two types:

  1.  Multidimensional arrays can be initialized by specifying the values of array elements enclosed within curly brackets for each row while the declaration of the array. Following is an array with 3 rows and each row has 2 columns.
    
    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 */
    }
    
    
  2.  Another way of initializing Multidimensional arrays using the var keyword, an array named a is declared with var keyword of two-dimensional integer type with values of each row element is assigned inside curly braces. Following is an array with 5 rows and each row has 2 columns.
    
    var a = [3][2]int{ {0,0}, {8,2}, {2,4}, {3,9},{4,7}}
    
    

Find the Length of an Array

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)

GO : Array
  •   Declare an array of any size
  •   Call len() function to return the length
  •   Example
    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
    

Check if Element Exists

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>

GO : Array

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

How to Filter Array Elements

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]

Copying Array from another Array

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]