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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.