runtime panic (index out of range)
GoCRITICALCommonRuntime

runtime error: index out of range [N] with length M

Quick Answer

Always verify the index is within bounds using len() before accessing elements, or iterate with range.

What this means

A panic triggered when accessing a slice, array, or string with an index that is negative or greater than or equal to the length.

Why it happens
  1. 1Accessing slice[i] where i >= len(slice)
  2. 2Off-by-one error in a manual index calculation

Fix

Bounds check before access

Bounds check before access
if i >= len(s) {
    return fmt.Errorf("index %d out of range", i)
}
v := s[i]

Why this works

Explicit bounds checking turns a hard panic into a soft, recoverable error.

Code examples
Guard accessgo
if idx < len(items) {
    fmt.Println(items[idx])
}
Iterate safely with rangego
for i, v := range items {
    fmt.Println(i, v)
}
Recovergo
defer func() {
    if r := recover(); r != nil {
        log.Println("index panic:", r)
    }
}()

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Go errors