Arrays in Golang
An array is a fixed-size sequence of elements of the same type. In this tutorial, we'll learn about arrays and some basic operations on arrays in Golang.
Initializing an Array in Golang
To initialize an array in Golang, we have to specify the type of the elements stored and the length of the array. Here's the general syntax:
var arrayName [length]elementType
By default, when we declare an array, the elements are initialized with their zero values.
Example: Initializing an array named fruits with three strings:
Code:
package main
import "fmt"
func main() {
var fruits = [3]string{"apple", "banana", "orange"}
fmt.Println(fruits)
}
In the above example, we have created an array named fruits and size 3.
Output:
[apple banana orange]
Accessing Array Elements
To access an element in an array, we can use the index operator [ ] with the desired index value. The index value must be within the range of the array.
Example: Accessing array elements in Golang:
Code:
package main
import "fmt"
func main() {
var fruits = [3]string{"apple", "banana", "orange"}
fmt.Println(fruits[0])
fmt.Println(fruits[2])
}
Output:
apple
orange
Modifying Array Elements
We can modify the value of an element in an array by assigning a new value to the corresponding index
Example: Modifying array elements in Golang:
Code:
package main
import "fmt"
func main() {
var fruits = [3]string{"apple", "banana", "orange"}
fruits[2] = "mango"
fmt.Println(fruits)
}
Output:
[apple banana mango]
Iterating over an Array
To iterate over the elements of an array, we can use a for loop and the array's length.
Example: Iterating over array elements in Golang:
Code:
package main
import "fmt"
func main() {
var fruits = [3]string{"apple", "banana", "orange"}
for i := 0; i < len(fruits); i++ {
fmt.Println(fruits[i])
}
}
In above code we used an for loop to iterate over the elements of the fruits array. It starts with i initialized to 0, and the loop continues as long as i is less than the length of the fruits array. Inside the loop, it prints the value of fruits[i].
Output:
apple
banana
orange