Arrays in Go are fixed-size sequences of elements of the same type. They provide a fundamental data structure for storing and manipulating collections of data efficiently.
In Go, you can declare an array by specifying its size and element type. Here's a basic syntax:
var arrayName [size]type
For example, to create an array of 5 integers:
var numbers [5]int
You can also initialize an array with values:
fruits := [3]string{"apple", "banana", "orange"}
Array elements are accessed using zero-based indexing. To access or modify an element:
numbers := [5]int{1, 2, 3, 4, 5}
fmt.Println(numbers[2]) // Output: 3
numbers[4] = 10
fmt.Println(numbers) // Output: [1 2 3 4 10]
The length of an array is part of its type and cannot be changed. Use the len()
function to get the array's length:
arr := [4]int{1, 2, 3, 4}
fmt.Println(len(arr)) // Output: 4
Go supports multi-dimensional arrays. Here's an example of a 2D array:
matrix := [3][3]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
fmt.Println(matrix[1][2]) // Output: 6
While arrays have a fixed size, Go Slices offer more flexibility with dynamic sizing. Slices are built on top of arrays and are more commonly used in Go programs.
range
keyword for easy iteration over arrays.Here's an example demonstrating common array operations:
package main
import "fmt"
func main() {
// Declare and initialize an array
numbers := [5]int{1, 2, 3, 4, 5}
// Iterate over the array
for i, num := range numbers {
fmt.Printf("Index: %d, Value: %d\n", i, num)
}
// Modify an element
numbers[2] = 10
// Print the modified array
fmt.Println("Modified array:", numbers)
// Get the length of the array
fmt.Println("Array length:", len(numbers))
}
This example showcases array declaration, initialization, iteration, modification, and length retrieval.
Arrays in Go provide a simple and efficient way to work with fixed-size collections of elements. While they have limitations compared to slices, arrays are useful in scenarios where the size of the collection is known and constant. Understanding arrays is crucial for mastering Go's data structures and building efficient programs.