TryBugHunt

panic: runtime error: index out of range

panic: runtime error: index out of range in Go means you attempted to access a Go slice or array at an index that is less than zero or greater than or equal to its length (len).

GoPattern: Off-by-one errors

How do I fix panic: runtime error: index out of range?

To fix panic: runtime error: index out of range in Go, locate the line causing the error and check the values right before it runs. Most occurrences happen because of indexing at len(slice) instead of len(slice) - 1. Apply a defensive check or safe fallback, make sure collections or objects exist before access, and verify return values from upstream functions.

1. Inspect bounds & typesPrint or inspect collection sizes and verify variables are not empty or None/undefined.
2. Guard with safe accessUse optional chaining (?.), dictionary get(), or guard conditions before dereferencing.
3. Trace upstream originsFind where the value was instantiated or returned rather than only patching the symptom.

What does panic: runtime error: index out of range mean?

Go performs bounds checks on all slice and array index operations. Unlike C or C++, accessing beyond the slice length does not silently corrupt memory or return undefined; it triggers a runtime panic immediately.

Why does panic: runtime error: index out of range happen?

1. Indexing at len(slice) instead of len(slice) - 1

Go slices are 0-indexed. The last valid element is at index len(slice) - 1.

Breaks

items := []string{"a", "b"}
last := items[len(items)] // panics with index [2] with length 2!

Works

items := []string{"a", "b"}
last := items[len(items)-1]

2. Accessing an empty slice

An empty slice has len 0, so any index access panics.

Breaks

var queue []int
first := queue[0] // panics!

Works

if len(queue) > 0 {
    first := queue[0]
    _ = first
}

How to find it in your own code

Always verify len(slice) > 0 before accessing indices. When looping with an explicit counter, ensure i < len(slice) rather than i <= len(slice), or prefer the idiomatic 'for i, val := range slice' syntax.

Try it: fix this bug

medium

panic: runtime error: index out of range [-1] with length 4

package main

import "fmt"

func getHashBucket(hash int, numBuckets int) int {
	// In Go, -5 % 4 evaluates to -1
	idx := hash % numBuckets
	buckets := make([]int, numBuckets)
	return buckets[idx]
}

func main() {
	fmt.Println(getHashBucket(-5, 4))
}
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Related error guides

View all off-by-one errors →