Go Arrays
Go - Arrays
Section titled “Go - Arrays”An array in Go is a numbered sequence of elements of a single, specific type with a fixed length. Think of it as a fixed-size container where each slot holds a value of the same type.
Key characteristics of Go arrays:
Arrays store their elements in a contiguous block of memory.
Declaring Arrays
Section titled “Declaring Arrays”You declare an array by specifying its size and the type of its elements:
var variableName [SIZE]elementTypeHere, SIZE must be a non-negative integer constant, and elementType is any valid Go type.
Example: Declare an array named scores to hold 5 integer values.
var scores [5]int // Declares an array of 5 integers, initialized to [0 0 0 0 0]Initializing Arrays
Section titled “Initializing Arrays”You can initialize an array during declaration using an array literal:
- Specify size and provide values:
var grades = [3]int{85, 92, 78} // Array of 3 ints
// Using short declaration syntaxnames := [4]string{"Alice", "Bob", "Charlie"} // Size 4, last element is "" (zero value)The number of values in the literal {...} cannot exceed the specified size.
- Let Go infer the size:
Use ... instead of a specific size, and the compiler will determine the array’s length based on the number of elements in the literal.
temperatures := [...]float64{19.5, 22.0, 21.7} // Array of 3 float64s, size inferred- Specify values at specific indices:
counters := [5]int{1: 10, 3: 30} // Array of 5 ints: [0 10 0 30 0]// Indices 0, 2, 4 get the zero value (0)Accessing and Modifying Array Elements
Section titled “Accessing and Modifying Array Elements”Access elements using the array name followed by the index in square brackets []. Remember that indexing starts at 0.
var data [3]int
data[0] = 100 // Assign 100 to the first elementdata[1] = 200data[2] = 300
firstValue := data[0] // Read the value of the first element (firstValue is 100)// data[3] = 400 // Compile-time error: index 3 out of bounds for array of size 3Example: Declaring, Initializing, and Accessing
Section titled “Example: Declaring, Initializing, and Accessing”Let’s work with an array of numbers:
package main
import "fmt"
func main() { // Declare and initialize an array of 5 integers numbers := [5]int{10, 20, 30, 40, 50}
fmt.Println("Original array:", numbers)
// Modify the element at index 2 numbers[2] = 35 fmt.Println("Modified array:", numbers)
// Access and print individual elements using a loop fmt.Println("\nAccessing elements individually:") for i := 0; i < len(numbers); i++ { fmt.Printf("Element[%d] = %d\n", i, numbers[i]) }
// Iterate using the range keyword (idiomatic Go) fmt.Println("\nIterating with range:") sum := 0 for index, value := range numbers { fmt.Printf("Index: %d, Value: %d\n", index, value) sum += value }
fmt.Printf("\nSum of elements: %d\n", sum)
// Get the length of the array using len() fmt.Printf("Length of array: %d\n", len(numbers))}Output:
Original array: [10 20 30 40 50]Modified array: [10 20 35 40 50]
Accessing elements individually:Element[0] = 10Element[1] = 20Element[2] = 35Element[3] = 40Element[4] = 50
Iterating with range:Index: 0, Value: 10Index: 1, Value: 20Index: 2, Value: 35Index: 3, Value: 40Index: 4, Value: 50
Sum of elements: 155Length of array: 5Arrays vs. Slices
Section titled “Arrays vs. Slices”Arrays have their uses, particularly when the exact number of elements is known at compile time and fixed. However, in idiomatic Go, slices are used much more frequently because of their flexibility (dynamic size).
Key differences to remember:
| Feature | Array ([N]T) | Slice ([]T) |
|---|---|---|
| Size | Fixed, part of the type | Dynamic, can grow/shrink |
| Passing to Functions | Pass-by-value (entire array copied) | Pass-by-value (slice header copied, points to same underlying array) |
| Declaration | var a [5]int, a := [...]int{1,2} | var s []int, s := []int{1,2}, make([]int, 5) |
| Common Usage | Less common, useful for fixed-size collections | Very common, flexible data sequences |
Further Array Concepts
Section titled “Further Array Concepts”While less common than single-dimensional arrays, Go also supports:
Multi-dimensional Arrays: Arrays of arrays, creating grid-like structures.
var matrix [2][3]int // A 2x3 grid of integersmatrix[0][1] = 5Passing Arrays to Functions: As mentioned, arrays are passed by value. If a function needs to modify the original array, you must pass a pointer to the array.
func modifyArray(arr *[3]int) { (*arr)[0] = 100 // Modify the original array via the pointer // arr[0] = 100 // Shortcut syntax also works}
func main() { myArray := [3]int{1, 2, 3} modifyArray(&myArray) // Pass the address (pointer) of the array fmt.Println(myArray) // Output: [100 2 3]}Due to the overhead of copying and the fixed size, passing slices is generally preferred over passing arrays (or pointers to arrays) unless the fixed-size property is specifically required.