go runtime ai_generated true

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

ID: go/slice-bounds-out-of-range

Also available as: JSON · Markdown
97%Fix Rate
98%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
121 active

Root Cause

Array/slice index exceeds its length.

generic

Workarounds

  1. 97% success Add bounds checking: if i < len(slice) { ... }
    Check index before accessing
  2. 93% success Use range-based for loop to avoid manual indexing
    for i, v := range slice { ... } — cannot go out of bounds

    Sources: https://go.dev/tour/moretypes/16

Dead Ends

Common approaches that don't work:

  1. Using recover() to catch the panic 70% fail

    Masks the bug; the slice access logic is wrong

  2. Pre-allocating a very large slice 80% fail

    Wastes memory; doesn't fix the indexing logic

Error Chain

Frequently confused with: