Skip to main content

How to Initialize an Array in Go

Updated 1 min readMarkdown

An array is one of the fundamental data structures for programming. By being able to store multiple different values of the same type, arrays are important for maintaining organization and efficiency of data. This post will go through the different ways one can initialize an array in Go.

Let's say that we want to initialize an array without assigning it a value. The code block below creates an empty integer array with a maximum length of 5:

var arr[5]int

When an integer array is initialized as empty, each position in the array has the value 0. Similarly, when a float array is initialized as empty, each position has the value 0.0.

We can also initialize an array and assign it a value at the same time. The code block below initializes an array that stores values 1, 3, and 4:

arr1 := [3]int{1, 3, 4}  // array "arr1" has length of 3

Lastly, we can also initialize and assign a value to a multi-dimensional array in the same way. The code block below initializes two 2x2 arrays: an empty one named "arr" and a non-empty one named "arr1":

var arr[2][2]int
arr1 := [2][2]int{
    {1, 1}, 
    {2, 2},
}

About the author

  • My name is Alissa and I am a software developer at RBC Capital Markets! I studied computer science and math at the University of Toronto and I am very interested in learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin

No comments yet. Be the first to comment.

More from this blog