Want to learn how to build better Go applications faster and easier? You can.
Check out my course on the Go Standard Library. You can check it out now for free.
In this article, we will cover the basics of creating and using arrays in Go. We will discuss the different types of arrays that can be created in Go, and provide examples of how to declare and initialize arrays.
In Go, you can declare an array by specifying its size and the type of elements it will contain. The syntax for declaring an array is as follows:
var arr [size]type
Here, arr
is the name of the array, size
is the number of elements in the array, and type
is the data type of each element. For example:
var numbers [5]int
This declares an array called numbers
with 5 integer elements.
Once you have declared an array, you can initialize its elements by assigning values to them. You can do this using the following syntax:
arr[i] = value
Here, i
is the index of the element you want to assign a value to, and value
is the value you want to assign. For example:
numbers[2] = 7
This sets the third element in the numbers
array to the value 7.
Once an array has been initialized, you can access its elements by using their indices. The syntax for accessing an element is as follows:
arr[i]
Here, i
is the index of the element you want to access. For example:
fmt.Println(numbers[2]) // prints 7
This prints the value of the third element in the numbers
array, which is 7.
In Go, you can create a slice of an array by specifying the indices of the elements you want to include in the slice. The syntax for slicing an array is as follows:
arr[i : j]
Here, i
and j
are the indices of the first and last elements you want to include in the slice, respectively. For example:
numbers := [5]int{1, 2, 3, 4, 5}
slice := numbers[1 : 3] // creates a slice containing elements 2-4
fmt.Println(slice) // prints [2, 3, 4]
This creates a slice called slice
that contains the values of the second, third, and fourth elements in the numbers
array, which are 2, 3, and 4, respectively.
Go also supports multi-dimensional arrays, which are arrays whose elements are themselves arrays. The syntax for declaring a multi-dimensional array is as follows:
var arr [size1][size2]type
Here, arr
is the name of the array, [size1]
and [size2]
are the sizes of each dimension, and type
is the data type of each element. For example:
var matrix [3][5]int
This declares a multi-dimensional array called matrix
with 3 rows and 5 columns, each containing an integer value.
Arrays are a fundamental part of the Go programming language, and they provide a powerful way to store and manipulate collections of data. By following the examples in this article, you should be able to create and use arrays in your own Go programs.