Practical Array Operations
Fundamental Array Manipulation Techniques
Element Access and Modification
// Creating a 2D array
var matrix [3][4]int
// Accessing and modifying elements
matrix[0][1] = 10
matrix[2][3] = 20
// Reading specific elements
value := matrix[1][2]
Iteration Strategies
Nested Loop Traversal
// Iterating through 2D array
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[i]); j++ {
fmt.Printf("%d ", matrix[i][j])
}
fmt.Println()
}
Range-based Iteration
// More concise iteration method
for _, row := range matrix {
for _, value := range row {
fmt.Printf("%d ", value)
}
fmt.Println()
}
Advanced Array Operations
// Transpose a matrix
func transposeMatrix(original [3][4]int) [4][3]int {
var transposed [4][3]int
for i := 0; i < len(original); i++ {
for j := 0; j < len(original[i]); j++ {
transposed[j][i] = original[i][j]
}
}
return transposed
}
Operation Types Comparison
Operation |
Description |
Time Complexity |
Access |
Direct element retrieval |
O(1) |
Iteration |
Traversing all elements |
O(n*m) |
Transformation |
Modifying array structure |
O(n*m) |
Memory Management Visualization
graph TD
A[Array Operations] --> B[Access]
A --> C[Modification]
A --> D[Transformation]
A --> E[Iteration]
Slice vs Array
// Prefer slices for dynamic operations
dynamicMatrix := make([][]int, 3)
for i := range dynamicMatrix {
dynamicMatrix[i] = make([]int, 4)
}
Common Use Cases
- Matrix calculations
- Game board representations
- Image pixel manipulation
- Scientific computing
- Data processing algorithms
Error Handling
// Bounds checking
func safeAccess(matrix [][]int, row, col int) (int, error) {
if row < 0 || row >= len(matrix) ||
col < 0 || col >= len(matrix[row]) {
return 0, fmt.Errorf("index out of bounds")
}
return matrix[row][col], nil
}
Advanced Techniques
Parallel Processing
// Concurrent array processing
func processMatrix(matrix [][]int) {
var wg sync.WaitGroup
for i := range matrix {
wg.Add(1)
go func(row []int) {
defer wg.Done()
// Process row concurrently
}(matrix[i])
}
wg.Wait()
}
Learning with LabEx
Enhance your Go programming skills by practicing multidimensional array operations in the LabEx interactive environment.