Start Coding

Topics

Go Arrays: Fixed-Size Sequences in Go

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.

Declaring and Initializing Arrays

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"}

Accessing and Modifying Array Elements

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]

Array Length

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

Multi-dimensional Arrays

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

Arrays vs. Slices

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.

Best Practices and Considerations

  • Use arrays when you need a fixed-size collection of elements.
  • For dynamic sizing, consider using slices instead.
  • Arrays are passed by value to functions, which can be inefficient for large arrays.
  • Use the range keyword for easy iteration over arrays.

Common Operations with 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.

Conclusion

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.