Practical Array Usage
Basic Array Operations
Element Access and Modification
numbers := [5]int{10, 20, 30, 40, 50}
firstElement := numbers[0] // Accessing first element
numbers[2] = 35 // Modifying third element
Iterating Arrays
// Traditional for loop
for i := 0; i < len(numbers); i++ {
fmt.Println(numbers[i])
}
// Range-based iteration
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
Common Array Manipulation Techniques
Array Copying
original := [5]int{1, 2, 3, 4, 5}
copied := original // Creates a full copy
Comparing Arrays
arr1 := [3]int{1, 2, 3}
arr2 := [3]int{1, 2, 3}
isEqual := arr1 == arr2 // Compares all elements
graph TD
A[Array Manipulation] --> B[Copying]
A --> C[Filtering]
A --> D[Transforming]
A --> E[Searching]
Practical Use Cases
Matrix Operations
// 2D array for matrix representation
matrix := [3][3]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
// Accessing matrix elements
element := matrix[1][2] // Returns 6
Operation |
Time Complexity |
Memory Impact |
Access |
O(1) |
Low |
Iteration |
O(n) |
Moderate |
Copying |
O(n) |
High |
Advanced Array Techniques
Passing Arrays to Functions
func processArray(arr [5]int) [5]int {
// Function that works with fixed-size array
for i := range arr {
arr[i] *= 2
}
return arr
}
graph LR
A[Array Optimization] --> B[Minimize Copies]
A --> C[Use Slices]
A --> D[Preallocate Memory]
A --> E[Avoid Unnecessary Iterations]
LabEx Recommended Practices
- Use arrays for fixed-size collections
- Prefer slices for dynamic data
- Be aware of copying overhead
- Choose appropriate iteration methods
Error Handling and Boundary Checks
func safeAccess(arr [5]int, index int) (int, error) {
if index < 0 || index >= len(arr) {
return 0, fmt.Errorf("index out of bounds")
}
return arr[index], nil
}
By understanding these practical usage patterns, developers can effectively leverage arrays in Go, balancing performance, readability, and type safety.