Arrays are fundamental data structures in Go, designed to store a fixed-size, ordered sequence of elements of the same type. They have a specific length that can’t be changed after being declared. Arrays are useful when working with a predetermined number of elements, such as when attempting to store the days of the week.
Defining Arrays
In Go, arrays are defined using the following syntax:
var arrayName [arrayLength]elementType
Here’s an example of defining an array of integers:
var numbers [5]intYou can also initialize the array elements while declaring the array itself:
var numbers = [5]int{1, 2, 3, 4, 5}If you don’t want to specify the length explicitly, use the ... construct:
var numbers = [...]int{1, 2, 3, 4, 5}In this case, Go determines the length of the array based on the number of elements.
Accessing and Modifying Array Elements
You can access and modify array elements using their index, which starts from 0. Here’s an example:
package main
import "fmt"
func main() {
var numbers = [5]int{1, 2, 3, 4, 5}
fmt.Println("The array elements are:", numbers)
fmt.Println("Element at index 2 is:", numbers[2])
numbers[2] = 10
fmt.Println("New element at index 2 is:", numbers[2])
fmt.Println("The modified array is:", numbers)
}In this example, we print the initial array, access and print the element at index 2, modify the element, and finally print the new value and the modified array.
Array Length and Iterating Over Arrays
You can find the length of an array using the built-in len() function. To iterate over an array, you can either use a traditional for loop or a for range loop:
package main
import "fmt"
func main() {
var numbers = [...]int{1, 2, 3, 4, 5}
fmt.Println("Array length is:", len(numbers))
fmt.Println("Printing array elements using for loop:")
for i := 0; i < len(numbers); i++ {
fmt.Println(numbers[i])
}
fmt.Println("Printing array elements using for range loop:")
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}In this example, we print the array’s length, iterate over the array using a for loop, and then iterate over the array again using a for range loop.
Please note that arrays in Go are value types. This means that when you assign an array to another variable, a new copy of the array is created. Similarly, when passing an array to a function, a copy of the array is passed rather than a reference.
In many cases, using slices (a reference to a section of an array) is preferred over arrays in Go. This is because slices are more flexible and efficient for working with dynamically-sized sequences of elements.