In this tutorial, we will learn about arrays in Go. We will cover the basics of declaring and using arrays, including accessing and modifying elements.
An array is a collection of elements of the same type stored in contiguous memory locations. It allows you to store multiple items under a single name and access them using an index.
The syntax to declare an array in Go is:
var arrayName [arraySize]type
where the collection
can be an array, slice, map, or string.
We will learn how to declare, initialize, access, and modify arrays in Go.
We have already seen the syntax to declare an array. For example, the following statement declares an integer array arr
of size 5.
var arr = [5]int
Now, by default the elements in integer array would be initialized to 0. Or you can specify the elements after the type in the curly braces as shown below. var arr = [5]int{1, 2, 3, 4, 5}
For example,
arr
with 5 elements.package main
import "fmt"
func main() {
var arr = [5]int{1, 2, 3, 4, 5}
for _, num := range arr {
fmt.Print(num, " ")
}
}
1 2 3 4 5
arr
with 5 elements.package main
import "fmt"
func main() {
var arr = [5]int{10, 20, 30, 40, 50}
fmt.Println("The third element is:", arr[2])
}
The third element is: 30
arr
with 5 elements.package main
import "fmt"
func main() {
var arr = [5]int{5, 10, 15, 20, 25}
arr[1] = 50
for _, num := range arr {
fmt.Print(num, " ")
}
}
5 50 15 20 25