Indexing and Updating
Understanding Array Indexing
In Go, array indexing starts from 0, allowing direct access and modification of individual elements using their index position.
Accessing Array Elements
Basic Element Access
package main
import "fmt"
func main() {
fruits := [4]string{"apple", "banana", "cherry", "date"}
// Accessing specific elements
firstFruit := fruits[0] // "apple"
thirdFruit := fruits[2] // "cherry"
fmt.Println(firstFruit, thirdFruit)
}
Updating Array Elements
Direct Index Assignment
package main
import "fmt"
func main() {
numbers := [5]int{10, 20, 30, 40, 50}
// Updating an element
numbers[2] = 35
fmt.Println(numbers) // [10 20 35 40 50]
}
Index Range and Bounds Checking
Operation |
Description |
Behavior |
Valid Index |
Within array length |
Element accessed/modified |
Invalid Index |
Outside array bounds |
Runtime panic occurs |
Safe Indexing Techniques
func safeIndexUpdate(arr []int, index int, value int) bool {
if index < 0 || index >= len(arr) {
return false
}
arr[index] = value
return true
}
Memory Representation of Indexing
graph LR
A[Array Memory] --> B[Index 0]
A --> C[Index 1]
A --> D[Index 2]
A --> E[Index n-1]
Common Indexing Patterns
Iterative Updates
package main
import "fmt"
func main() {
scores := [5]int{10, 20, 30, 40, 50}
// Updating all elements
for i := 0; i < len(scores); i++ {
scores[i] *= 2
}
fmt.Println(scores) // [20 40 60 80 100]
}
Error Handling in Indexing
Panic Prevention
func updateElementSafely(arr []int, index, value int) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Index out of range")
}
}()
arr[index] = value
}
Best Practices
- Always validate index before access
- Use range-based loops for safer iteration
- Consider slices for dynamic length requirements
By mastering these indexing techniques, you'll write more robust Go code. LabEx encourages continuous practice to improve your skills.