Friday, November 23, 2018

Learn Golang Tutorials - Arrays Beginner Guide with examples

This blog covers Beginner guide to Arrays in Golangauage with examples.

Golang Arrays Introduction

An array is one of the data structure which contains a collection of elements with referred as the same name and grouped under same data type. It is the fixed size in length.
The following are topic covered in this post
  • Array syntax
  • Array Declaration 
  • Declare with Array Literals
  • Initialization with array ellipse
  • Access elements of an array
  • Size of array
  • Iterate elements using for loop and range keyword
  • Multidimensional arrays creation with literals, Shorthand syntax
  • Array struct or object example - Create, Access, iterate
  • Find Array variable type
  • Arrays types are not assignable with different length
  • Arrays are value types
  • Linear search example
  • Popular array runtime errors
Following are some of the keynotes of arrays in go language
  • The array contains a list of elements stored in Sequential order of same data type
  • Size of the array is fixed
  • Elements in the array stored on the sequential order and can be accessed using index 0
  • Declaring a variable of the array be declared of same like a normal variable with [] before datatype
  • length of an array  can be find using sizeof() method
Arrays can contain primitive types and custom types. The values stored in memory are side by side. Arrays can be single or multidimensional arrays.

Syntax

var variable-name [size]datatype // single dimensional array
var variable-name [size][size]datatype // Multi dimensional array
var is a keyword in golang, used to declare a variable
variable-name is the name of the variable
size is a fixed size of an array,
the datatype can be a primitive type or custom type.

Array Declaration, Creation 

Array declaration contains var keyword, variable name and data type We can declare an array with fixed size n of type T.
var array-variable [n]T
Once an array is declared with size n, Size will not be grown as this fixed.
Let us see an example of declaring integer array with size 5
var arr[5] int
Following is the example of array declaration
package main

import "fmt"

func main() {
 // An array with 5 integers
 var v1 [5]int
 fmt.Println(v1)
 // An array of 5 float
 var v2 [5]float64
 fmt.Println(v2)
 // An array of 5 boolean
 var v3 [5]bool
 fmt.Println(v3)
 // An array of 5 string
 var v4 [5]string
 fmt.Println(v4)
 // An array of 5 byte
 var v5 [5]byte
 fmt.Println(v5)
 // An array with 5 complex numbers
 var v6 [5]complex128
 fmt.Println(v6)
}
The output of the above program is
[0 0 0 0 0]
[0 0 0 0 0]
[false false false false false]
[    ]
[0 0 0 0 0]
[(0+0i) (0+0i) (0+0i) (0+0i) (0+0i)]
In the above program, an array is declared with different types and an array is not assigned with values, Go compiler assumes and assigns default zero values to each element of array type. Zero values are for zero is assigned with Numeric values, boolean values are assigned with false, String with an empty string, Complex128 with (0+0i) values.

Declare array and initialization with array Literal 

Sometimes, size of an array and type of elements are already known, Array literal can be used. This is another way of creating and initializing values in a single step.
// Declare and initialize array values
var arr = [5]int{21, 3, 1, 4, 2}
It contains two parts, One left hand contains the name of the array variable. Right-hand side part is called array literal. here array variable is not declared with arr [5]int, the compiler can infer from array values. The same can be rewritten using shorthand array variable declaration syntax. Here var is not declared like any variable declaration. the array variable is declared and initialized using this syntax
//Short hand array variable declaration and initialize
arr := [5]int{21, 3, 1, 4, 2}
The below program code, an array is created with shorthand variable with a fixed size of 5. But only 3 values are initialized. Remaining two values are filled with default zero values
// Short hand Array variable Creation and initialized with values
arr := [5]int{5, 3, 1}
// Display length to console
fmt.Println(len(arr))

Declare an array with ellipse symbol 

The array can be declared and initialized with literal syntax, but the length of an array is not specified but with ellipse symbol. Compiler find out the length based the number of elements
package main

import "fmt"

func main() {
 // Short hand Array variable Creation and initialized with values
 arr := [...]int{5, 3, 1}
 // Display length to console
 fmt.Println(len(arr))
 fmt.Println(arr)

}
Output is
3
[5 3 1]

Assign elements and access elements using the index

Arrays store the elements in sequential order. The index of an array always starts with 0 and last element is size of the array -1. In the above program, Array of 5 integers is created, some values v1[2] are initialized with default automatically. Remaining elements are assigned explicitly The elements in the array are accessed using the index - v1[index]
package main

import "fmt"

func main() {
 // An array with 5 integers
 var v1 [5]int

 v1[0] = 5
 v1[1] = 2
 v1[3] = 1
 v1[4] = 4
 fmt.Printf("v1[0] = %d, v1[1] = %d, , v1[2] = %d, v1[3] = %d,  v1[4] = %d\n", v1[0], v1[1], v1[2], v1[3], v1[4])
 fmt.Println("v1= ", v1)

}
The output of the above program is
v1[0] = 5, v1[1] = 2, v1[2] = 0,, v1[3] = 1,  v1[4] = 4
v1=  [5 2 0 1 4]

a length of an array - Number of elements

Often we need to find the number of elements in the array. len() is the function used to find the length of the array. In the below program code, First is printed the length of the array Next added an element to array and printed the length
package main

import "fmt"

func main() {
 // Array Creation and initialized with values
 arr := []int{5, 3, 11, 1}

 // Display length to console
 fmt.Println(len(arr))

 // Assign an value to array
 arr = append(arr, 61)
 fmt.Println(len(arr))

}
The output of the above program code is
4
5

Iterate an element of an array using for loop 

sometimes we need to loop all the elements of an array. Golang has for loop used to iterate elements. You can check another article on for loop in golang. This is a basic for loop example to iterate array elements. len() function is used to retrieve the number of elements of an array
package main

import "fmt"

func main() {
 // Array Creation and initialized with values
 arr := []int{5, 3, 11, 1}

 for i := 0; i < len(arr); i++ {
  fmt.Println(arr[i])
 }
}
The output of the above program code execution is
5
3
11
1

Iterate an element of an array using a range 

This is another way to iterate array elements using range keyword in for loop. range keyword in array loop returns two elements during iteration, First element is an index, second is actual element.


package main

import "fmt"

func main() {
 // Array Creation and initialized with values
 arr := []int{5, 3, 11, 1}

 for index, element := range arr {
  fmt.Printf("%d  = %d\n", index, element)
 }

}
The output of the above program code execution is
0  = 5
1  = 3
2  = 11
3  = 1
if we don't need index value, In that case, We will use back identifier(_) with for range syntax

An array of arrays - Multidimensional Arrays

Like any other programming language, Go language has supports for Multidimensional arrays. Multidimensional arrays are arrays that contain arrays. Here is a syntax of multidimensional arrays

var variablename [n1][n2]...[n3] type
variable name is identifier type is a primitive type or custom type Let us see an example for creating two-dimensional integer arrays. if these elements are initialized explicitly, the compiler assigns zero values of element type default
var arr [2][2] int
Following example explains about usage of multidimensional arrays
  • Declare and create Two-dimensional arrays using simple, literals, shorthand syntax
  • Initialize two-dimensional arrays
  • Accessing elements of two-dimensional arrays
  • Iteration of two-dimensional arrays
package main

import "fmt"

func main() {
 /* Two dimensional array declare and initilize */
 var array1 = [3][2]int{{0, 1}, {1, 2}, {2, 3}}
 // shorthand two dimensional array variable declaration
 array2 := [2][2]int{{0, 1}, {1, 2}}
 var i, j int
 /* Iterating elements array1 */
 for i = 0; i < 3; i++ {
  for j = 0; j < 2; j++ {
   fmt.Printf("array1[%d][%d] = %d\n", i, j, array1[i][j])
  }
 }
 /* Iterating elements array2 */
 for i = 0; i < 2; i++ {
  for j = 0; j < 2; j++ {
   fmt.Printf("array2[%d][%d] = %d\n", i, j, array2[i][j])
  }
 }
}
The output of the above program is
array1[0][0] = 0
array1[0][1] = 1
array1[1][0] = 1
array1[1][1] = 2
array1[2][0] = 2
array1[2][1] = 3
array2[0][0] = 0
array2[0][1] = 1
array2[1][0] = 1
array2[1][1] = 2

Object Array creation - Struct example

Like normal primitive array creation, Struct or custom object array can be created. Declared and initialized with the same syntax like primitive arrays Following is an example for creating Struct array and accessing elements of struct
package main import "fmt" type employee struct { id int name string } func main() { emps := []employee{ { name: "kiran", id: 1, }, { name: "john", id: 2, }, } fmt.Println(emps) }
The output of the above program is
[{1 kiran} {2 john}]

Check Array Variable data type

Like variable type check, Array type can be checked using Reflection API -reflect.TypeOf() or fmt.Printf with %T formatting following is an example for finding Array variable type
package main

import (
 "fmt"
 "reflect"
)

func main() {
 v4 := []string{"one", "two", "three"} //// string array variable
 fmt.Println("============== Using Reflection ==============")
 fmt.Println("string array variable type: ", reflect.TypeOf(v4))
 fmt.Println("============== Using Printlnf formatting ==============")
 fmt.Printf("%T\n", v4)

}
The output of the above program code execution is
A:\Golang\work>go run array.go
============== Using Reflection ==============
string array variable type:  []string
============== Using Printlnf formatting ==============
[]string

Arrays types are not assignable with different length

Array contains two important things ie type and lenth. So array size is part of type. Once array declared, size and type array not assignable to another array. In the below code, the compiler treats two arrays - array2 [5] and array1 [2] are different since size is an part of type of an array. array1 is assigned to of different array type, THis will not be allowed and gives compilation error - cannot use array1 (type [2]int) as type [5]int in assignment
package main

func main() {
 array1 := [2]int{2, 3}
 var array2 [5]int
 array2 = array1
}
The output of the above program code is


A:\Golang\work>go run array.go
# command-line-arguments
.\array.go:6:9: cannot use array1 (type [2]int) as type [5]int in assignment 

array assignment is value types not reference types 

Arrays in Golang are based on value based types. When you assign an array to new variable, The Entire values are copied to a new array variable. if you modify or change in original array, New array will not be changed. and also if any changes to new array will not reflect changes in original array.
package main

import "fmt"

func main() {
 array1 := [...]string{"one", "two", "three"}
 array2 := array1 //array assigment values are copied, not reference
 array2[0] = "three"
 fmt.Println("array1: ", array1)
 fmt.Println("array2: ", array2)
}
The output of the above code is

A:\Golang\work>go run array.go
array1:  [one two three]
array2:  [three two three]

Check an element search/contains in an array 

Golang don't have any predefined function to check element exists an array In the following code, contain function is declared, return true - if element exists, false- not exists Following is linear search with element checking example
package main

import "fmt"

// Check element exists in array
func contain(str [3]string, element string) bool {
 for _, value := range str {
  if element == value {
   return true
  }
 }
 return false
}
func main() {
 array1 := [...]string{"one", "two", "three"}
 fmt.Println(contain(array1, "one"))  // true
 fmt.Println(contain(array1, "one1")) // false
}
Output is
true
false
This will also be used in passing an array to function.

Array runtime errors 

  • panic: runtime error: index out of range - This will be thrown when you are accessing index with a value greater than array length -1 
  • array1 declared and not used - Compiler gives an error when a variable is declared but not used.
  • use of [...] array outside of array literal-  ellipse symbol is not used in function declaration with string array argument. only used with string literals

Related article


EmoticonEmoticon