Panic: runtime error: index out of range error in Golang

In Golang, the "panic: runtime error: index out of range" error occurs when you try to access an element of an array or slice that is out of bounds. This error indicates that you are trying to access an element that does not exist in the given array or slice.

Let's consider an example to understand this error. Consider the following Golang program:

Example

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    fmt.Println(numbers[6])
}

In this program, we define a slice numbers with five integer elements. We then try to access the sixth element of the slice, which is out of bounds.

When we try to compile and run this program, we will encounter the following error:

Output

panic: runtime error: index out of range [6] with length 5

This error occurs because we are trying to access an element at index 6, which is out of bounds for the numbers slice. The slice has a length of 5, so the valid indexes are 0 to 4.

To fix this error, we need to ensure that we only access elements that are within the bounds of the slice, like this:


Example

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    if len(numbers) > 6 {
        fmt.Println(numbers[6])
    } else {
        fmt.Println("Index is out of range")
    }
}

In this modified program, we check the length of the numbers slice before accessing the sixth element. If the length is greater than 6, we print the sixth element. Otherwise, we print a message indicating that the index is out of range. This code will compile and run without any errors.

In summary, the "panic: runtime error: index out of range" error in Golang occurs when you try to access an element of an array or slice that is out of bounds. To fix this error, you need to ensure that you only access elements that are within the bounds of the array or slice.


Most Helpful This Week