How to Fix panic: runtime error: index out of range in Go

Go raises panic: runtime error: index out of range when you try to access an element in a slice or an array using an index that is either less than 0 or greater than or equal to the length of the slice/array.

Reproduce the error

package main

import "fmt"

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

Output

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

How to fix the error?

To fix panic: runtime error: index out of range error, check if the index is within the valid range before accessing the element.

package main

import "fmt"

func main() {
 numbers := []int{1, 2, 3}
 index := 3

 if index >= 0 && index < len(numbers) {
   fmt.Println(numbers[index])
 } else {
   fmt.Println("Index out of range")
 }
}

Output

Index out of range

You can see that we checked if the index was out of range and if it was, we printed the statement otherwise, we printed the element.

That’s it.