Golang Array tutorials with examples

This blog is a beginner guide to Arrays in Go language with examples.

Arrays in Go language

An array is a data structure that contains a collection of elements of the same data type. It can be declared as single or multi-dimensional It is a fixed size in length.

Following topics are covered in this article.

  • Array syntax
  • Array Declaration
  • Declare with Array Literals
  • Initialization with array using ellipse
  • Access elements of an array
  • Size of array
  • Iterate elements using for loop and range keyword
  • Multidimensional arrays creation with literals, a 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

Array Notes in Go:

  • The array contains a collection of elements, stored in Sequential order of the same data type
  • Size of the array is fixed
  • Elements in the array are stored in the sequential order
  • The elements can be accessed using the index, which is always starts with 0 and the last element is the size of the array -1.
  • Declare Array variable is same as a normal variable
  • length of an array can be found using the sizeof() method
  • Arrays can be single or multidimensional arrays.

Arrays contains only primitive and custom types. The values stored in memory are side by side.

Array Syntax

The array can be created in either single or multidimensional arrays. The syntax of array declaration

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

How to declare and create an array in Golang?

Array declaration contains var keyword, followed by variable name, square brackets with size, and datatype.

var variablename [size]T

Array size declared with [size], datatype declared with T. Size is fixed, not growable.

Let us see an example of declaring an integer array with a size of 5

var arr[5] int

Following is the example of an 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
  • an array is not assigned with values, hence, the 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.

How to Declare array and initialization with array Literal?

Sometimes, the 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 a 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))

How to Declare an array with an ellipse symbol?

The array can be declared and initialized with literal syntax, but the length of an array is not specified.

We can also declare an array with an ellipse symbol. The compiler finds out the length based on the number of elements

Example:

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:

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 the last element is the size of the array -1.
  • In the below program, an array of 5 integers is created, and 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]

How to find 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 is, Next added an element is to the array, and print the length of an array.

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

How to Iterate an element of an array using for loop

Sometimes we need to loop all the elements of an array.

Golang has a for loop used to iterate elements. You can check another article on for loop in golang 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

How to Iterate an element of an array using a range in Golang

It is another way to iterate array elements using the range keyword in for loop.

The range keyword in the array loop returns two elements during iteration, First, the element is an index, and the second is an 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 an index value, In that case, We will use the back identifier(_) with for range syntax

An array of arrays - Multi dimensional Arrays in Golang

Like any other programming language, Go language has support for Multi dimensional arrays. Multi dimensional arrays are arrays that contain arrays.

Here is a syntax of multidimensional arrays


var variablename [n1][n2]...[n3] type

the 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 do initialize explicitly, the compiler assigns zero values of element type default

var arr [2][2] int

The following example explains about usage of multi-dimensional arrays.

  • Declare and create Two-dimensional arrays using the simple, literal, 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

How to create Array Objects in Golang - Struct example

Like normal primitive array creation, Struct or custom object array can be created. Declared and initialized with the same syntax as primitive arrays.

Following is an example of creating a Struct array and accessing elements of the 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}]

How to Check Array Variable data type in Golang?

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

Error in golang - Arrays types are not assignable with different length

  • Array contains two important things ie type and length.
  • Array size is part of the type.
  • Once the array is declared, the size and type array is not assignable to another array.

In the below code, the compiler treats two arrays - array2 [5] and array1 [2] are different since the size is part of the type of array.

array1 assigns to different array types,

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

Error in golang -array assignment is value types, not reference types

Arrays in Golang are based on value-based types. When you assign an array to a new variable, The Entire values are copied to a new array variable.

If you modify or change the original array, the New array does not change. and also if any changes to the new array will not reflect changes in the 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]

How to Check an element search/contains in an array?

Golang doesn’t have any predefined function to check element exists in an array.

In the following code, contain function is declared, return true - if element exists, false- not exists.

Following is a linear search with an 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

It passes an array to function.

Array runtime errors

  • panic: runtime error: index out of range - It throws when you are accessing an 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 does not use in function declaration with a string array argument. Only used with string literals

Conclusion

We have learned array with simple and multiple dimensional arrays with different syntax.