An array is a data structure used to store similar elements at contiguous memory locations. What we meant by contiguous memory location is that the elements will be present next to each other in the memory and not at random places. So, it is easy to get to the desired element from any element by directly jumping to that memory location and accessing that element in O(1) time.
But why do we need arrays?
- Suppose, we want to store alphabets from A-Z which will be used later in the code. So, now, storing each of the alphabets in a unique variable and then further use them in the code will be quite cumbersome and our code will also be a bit messier. Using Arrays here will solve these problems as we will only be naming the array variable once and store all of the alphabets in that array and our code will also be a bit cleaner.
- Arrays allows us random access of the elements.
In this post, we are going to look at the below points
- How to declare an array in Go Language?
- Zero values in Arrays
- Declaring and initializing array in the same lime ( Array literal )
- Initializing an Array using Ellipsis ( … )
- Print whole array at once using fmt package
- Multi-Dimensional Arrays
- Looping over arrays
So, let’s go through it one by one.
How to declare an array in Go Language?
Arrays can hold only a specific number of elements and they cannot grow or shrink. To declare a variable that holds an array, we need to specify the number of elements it will contain in the square brackets( [ ] ), followed by the type of elements it will contain.
Syntax for declaring an array variable
var array_variable_name [n]elements_data_type
Example
var arr [7]int
Now, to set or retrieve a value, we will need to specify which element we want to set or retrieve. Elements in an array are numbered starting from 0, which is also known as the element’s index. So, 1st element will have an index of 0, 2nd element will have an index of 1, and so on.
Code Example
package main
import "fmt"
func main() {
// declaring an array
var arr [5]int
// setting element values in the array
arr[0] = 12
arr[1] = 65
arr[2] = 13
arr[3] = 34
arr[4] = 42
fmt.Println("Value at the index 3 or value of 4th element is:", arr[3])
}
Output –
Value at the index 3 or value of 4th element is: 34
Zero values in Arrays
As we know about a variable, if we only declare a variable and do not initialize or assign any value to it, then a default value is assigned corresponding to the type of the variable. The same thing happens with arrays too. All of the values inside an array will be initialized to the zero value of the type that the array holds.
package main
import "fmt"
func main() {
// declaring an array
var arr [2]int
// setting value at index 0
arr[0] = 12
fmt.Println("Value present at index 0 is:", arr[0])
fmt.Println("Value present at index 1 is:", arr[1])
}
Output –
Value present at index 0 is: 12
Value present at index 1 is: 0
Declaring and initializing array in the same lime ( Array literal )
If you know the elements beforehand you will be entering in the array afterward, we can do this in just one line using array literals with a bit of help from shorthand declaration.
Syntax
arr := [n]type_of_elements{element1,element2,...,elementn}
Code Example
package main
import "fmt"
func main() {
// declaring an array
arr := [3]int{12, 43, 23}
// getting values
fmt.Println("Value present at index 0 is:", arr[0])
fmt.Println("Value present at index 1 is:", arr[1])
fmt.Println("Value present at index 2 is:", arr[2])
}
Output –
Value present at index 0 is: 12
Value present at index 1 is: 43
Value present at index 2 is: 23
Initializing an Array using Ellipsis ( … )
If you want to declare and initialize the array using shorthand declaration in a single line but don’t want to count the number of elements required for this type of declaration, then we have an alternative. We can use the ellipsis symbol (…) in place of writing the length within the square brackets ( [ ] ).
package main
import "fmt"
func main() {
// declaring an array
arr := [...]int{12, 43, 23}
// getting values
fmt.Println("Value present at index 0 is:", arr[0])
fmt.Println("Value present at index 1 is:", arr[1])
fmt.Println("Value present at index 2 is:", arr[2])
}
Output –
Value present at index 0 is: 12
Value present at index 1 is: 43
Value present at index 2 is: 23
Print whole array at once using fmt package
If we want to print the whole array, then we don’t have to run the for loop over all of the elements and print them one by one. We can use the Println function of fmt package to print the whole array at once as shown below
package main
import "fmt"
func main() {
// declaring an array
arr := [3]int{12, 43, 23}
// getting values
fmt.Println("Array:", arr)
}
Output –
Array: [12 43 23]
Multi-Dimensional Arrays
An array is a linear data structure but we can create multidimensional arrays as well which is sometimes also called arrays of arrays. We can create a 2-D, 3-D, 4-D, and up to any dimensional numbers, keeping in mind the maximum space that can be allocated to it.
Syntax for declaring the multi-dimensional arrays
var array_variable_name [m1][m2]...[mN]type
And like in 1D arrays, we can also declare a multidimensional array using the shorthand declaration.
package main
import "fmt"
func main() {
// declaring a 2D array using shorthand declaration
arr := [3][2]int{{12, 45}, {23, 11}, {12, 43}}
// getting values
fmt.Println("Value at index row 2 and column 1 is:", arr[1][0])
var arr2 [3][2]int
arr2[0][0] = 23
arr2[0][1] = 64
arr2[1][0] = 87
arr2[1][1] = 23
arr2[2][0] = 54
arr2[2][1] = 65
fmt.Println("Printing whole array named arr2:", arr2)
}
Output –
Value at index row 2 and column 1 is: 23
Printing whole array named arr2: [[23 64] [87 23] [54 65]]
Looping over arrays
We can easily loop over arrays using for loop just like in any other programming language.
package main
import "fmt"
func main() {
// declaring an array
arr := [3]int{12, 43, 23}
for i := 0; i <= 2; i++ {
fmt.Println("Value at index", i, "is:", arr[i])
}
}
Output –
Value at index 0 is: 12
Value at index 1 is: 43
Value at index 2 is: 23
We have to take care of one thing is that we do not go out of the range while accessing an index. Like, we won’t be able to access an element present at index 6 if there are only 3 elements present in the array. If we try to access an index outside of the array, then it will cause a panic ( an error that occurs while our program is running ).
package main
import "fmt"
func main() {
// declaring an array
arr := [3]int{12, 43, 23}
for i := 0; i <= 3; i++ {
fmt.Println("Value at index", i, "is:", arr[i])
}
}
Output –
panic: runtime error: index out of range [3] with length 3
goroutine 1 [running]:
main.main()
D:/codekru.go:11 +0x189
exit status 2
Here we tried to access the element present at index 3 which is outside of the array. So, it caused the program to panic.
There is a much easier way of iterating over arrays using the for…range loop which we have covered in this post.
Hope you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.