Start learning free

LESSON 108 OF 671 · ARRAYS I

Exceeding static array's bounds in Go

Lesson

When accessing array data with indices, the most common problem we can run into is exceeding the array's bounds.

Remember, the items of an array are indexed from 0 to length - 1. Any index which is not in this range is invalid.

When you try to access an item with an invalid index, Go refuses to compile the program when the index is a constant it can check, and panics at run time when the index is only known while the program runs:

myArray := [3]int{50, 40, 30}

// Valid indices: 0, 1, 2
fmt.Println(myArray[0]) // Output: 50
fmt.Println(myArray[2]) // Output: 30

// Invalid indices: 3, 30, -1
fmt.Println(myArray[3])  // compile error: invalid argument: index 3 out of bounds [0:3]
fmt.Println(myArray[30]) // compile error: invalid argument: index 30 out of bounds [0:3]
fmt.Println(myArray[-1]) // compile error: invalid argument: index -1 (constant of type int) must not be negative

If the index is stored in a variable (for example i := 3 and then myArray[i]), the program compiles but crashes when it runs, with panic: runtime error: index out of range [3] with length 3.


As programmers, we always want to make sure that we don't exceed one array'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.


STEP 1 OF 1
    Ctrl + Enter to check