Arrays in GO Tutorial

Udemy Generic 728x90


In this tutorial we will learn the concept of Arrays in GoLang and process to implement them via some simple examples.



Array in GO Language can be defined as a variable having a bundle of multiple values of same data type.

Arrays use contiguous memory allocation model. Suppose we have an array a[10] with 10 values then all the 10 values will be assigned memory block with continuous memory addresses.   


Step 2


The type [n]T is an array of n values of type T.

Syntax [n]T shows an array having n values of datatype T. So the expression ,
var arr[10]int
declares a variable arr as an array of type int with a total 10 values.

Since array’s length is a part of array declaration, so arrays can not be resized in GO language.

Step 2.1

Example 1

A Simple Example to illustrate array implementation in GO : 

<br />
package main<br />
import &quot;fmt&quot;</p>
<p>func main() {</p>
<p>    var a [5]string<br />
    a[0] = &quot;Hey&quot;<br />
    a[1] = &quot;Guys,&quot;<br />
    a[2] = &quot;This&quot;<br />
    a[3] = &quot;is&quot;<br />
    a[4] = &quot;Go.&quot;</p>
<p>    fmt.Println(&quot;Length of array : &quot;, len(a))<br />
    fmt.Println(&quot;Value at index 2: &quot;, a[2])<br />
    fmt.Println(&quot;Array : &quot;,a)<br />
}<br />

Step 2.2


To execute the code create a file named arrays.go and copy the above code in that file and then run the below command in terminal. 

<br />
$ go run arrays.go<br />

Step 2.3


Length of array :  5
Value at index 2 :  This
Array : [Hey Guys, This is Go.]

In the above example we declared an array a of type string that will contain a max of 5 string values. So here we can see that the data type and the length of an array are the part of array declaration.

To insert a value in array at an index i we can set the index of array with value, i.e., a[i] = value. Also we can get a value at an index by a [i].

Arrays in GO have a built in function len that will return the length of the array.


Step 3

Multidimensional array

Array types in Go are single dimensional but we can also create multidimensional arrays in GO.

Step 3.1

Example 2

A Simple Example to illustrate multidimensional array implementation in GO : 

<br />
package main<br />
import &quot;fmt&quot;</p>
<p>func main() {<br />
     var multi [3][2]int<br />
    for i := 0; i &lt; 3; i++ {<br />
        for j := 0; j &lt; 2; j++ {<br />
            multi[i][j] = i + j<br />
        }<br />
    }<br />
    fmt.Println(&quot;Length: &quot;, len(multi))<br />
    fmt.Println(&quot;Value at index 1 of subarray at index 1 :&quot;, multi[1][1])<br />
    fmt.Println(&quot;Multi-dimensional array: &quot;, multi)<br />
}<br />

Step 3.2


<br />
$ go run multiArray.go<br />

Step 3.3


Length:  3
Value at index 1 of subarray at index 1 : 2
Multi-dimensional array:  [ [0 1] [1 2] [2 3] ]


Udemy Generic 728x90

Spread the word. Share this post!