Index and update elements
Index and update elements
Array indexes start at zero. For length N, valid indexes satisfy 0 <= i < N. Use a[i] to read and a[i] = value to update an element.
package main
import "fmt"
func main() { scores := [3]int{70, 80, 90} fmt.Println(scores[0], scores[len(scores)-1]) scores[1] += 5 fmt.Println(scores)}The last index is len(scores)-1, not len(scores). A constant out-of-range index is rejected at compile time. An out-of-range variable index causes a run-time panic.
Expected output:
70 90[70 85 90]Check bounds first
package main
import "fmt"
func lookup(a [3]int, i int) (int, bool) { if i < 0 || i >= len(a) { return 0, false } return a[i], true}func main() { a := [3]int{11, 22, 33} fmt.Println(lookup(a, 2)) fmt.Println(lookup(a, -1)) fmt.Println(lookup(a, 3))}The bool result distinguishes an invalid index from a valid zero value. A zero-length array has no valid index. Validate untrusted indexes before accessing elements.
Expected output:
33 true0 false0 falseTry it locally
Create [3]int{4,5,6}. Set the first element to 10 and add 2 to the last element using len. Print the array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Arrays 02: Index and update elements
Check the lesson objective before moving on.
What is the last valid index of [5]int?
What happens when a variable index equals the array length?