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.
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
To fix this 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 Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.