How to Initialize an Array in Go
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},
}
Subscribe to my newsletter
Read articles from Alissa Lozhkin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Alissa Lozhkin
Alissa Lozhkin
My name is Alissa and I am a fourth-year computer science and math student at the University of Toronto! I am very interested in computer science and software development, and I love learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin