When accessing slice data with indices, the most common problem we can run into is exceeding the slice's bounds.
Remember, the items of a slice are indexed from 0 to size - 1. Any index which is not in this range is invalid.
When you try to access an item with an invalid index, Go panics (the program crashes with a run-time error):
ourArray := []int{50, 40, 30}
// Valid indices: 0, 1, 2
fmt.Println(ourArray[0]) // Output: 50
fmt.Println(ourArray[2]) // Output: 30
// Invalid indices: 3, 30, -1
i := 3
fmt.Println(ourArray[i]) // panic: runtime error: index out of range [3] with length 3
i = 30
fmt.Println(ourArray[i]) // panic: runtime error: index out of range [30] with length 3
i = -1
fmt.Println(ourArray[i]) // panic: runtime error: index out of range [-1]
(Each line panics when it runs, so in a real program the first one stops everything. A constant index such as ourArray[-1] is rejected by the compiler even earlier.)
As programmers, we always want to make sure that we don't exceed one slice's bounds in our programs.
Assignment
Follow the Coding Tutorial and let's play with some arrays.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
