Go Array Basics
Understanding Array Fundamentals
In Go, arrays are fixed-length, ordered collections of elements with the same data type. Unlike dynamic languages, Go arrays have a strict, predefined length that cannot be changed after declaration.
Array Declaration and Initialization
Basic Declaration Syntax
var numbers [5]int // Declares an array of 5 integers
var matrix [3][4]int // Declares a 2D array
Initialization Methods
// Method 1: Direct initialization
fruits := [3]string{"apple", "banana", "orange"}
// Method 2: Partial initialization
scores := [5]int{1: 10, 3: 30}
// Method 3: Using ellipsis
colors := [...]string{"red", "green", "blue"}
Array Characteristics
Characteristic |
Description |
Fixed Length |
Cannot be resized after creation |
Type Safety |
All elements must be same type |
Zero Value |
Automatically initialized with zero values |
Memory Efficiency |
Contiguous memory allocation |
Memory Representation
graph LR
A[Array Memory Layout] --> B[Contiguous Memory Block]
B --> C[Element 1]
B --> D[Element 2]
B --> E[Element 3]
B --> F[Element N]
Key Limitations
- Fixed size cannot be changed
- Passing entire array copies entire data
- Limited dynamic manipulation
Arrays in Go are value types, meaning when passed to functions, a complete copy is created. For large arrays, this can impact performance significantly.
func processArray(arr [1000]int) {
// Entire array is copied
}
Best Practices
- Use slices for dynamic collections
- Prefer slice over array when possible
- Be mindful of memory usage with large arrays
Example: Array Operations
package main
import "fmt"
func main() {
// Array declaration
numbers := [5]int{10, 20, 30, 40, 50}
// Accessing elements
fmt.Println(numbers[2]) // Prints 30
// Iterating through array
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
Conclusion
Understanding Go array basics is crucial for effective memory management and performance optimization. While arrays provide a foundation, slices offer more flexibility in most scenarios.
Note: LabEx recommends practicing these concepts to gain deeper insights into Go array handling.