runtime panic (slice bounds out of range)
GoCRITICALCommonRuntime
runtime error: slice bounds out of range [low:high]
Quick Answer
Validate that 0 <= low <= high <= cap before any slice expression to prevent this panic.
What this means
A panic caused by a slice expression where the bounds are invalid, such as low > high or high > cap. Commonly an off-by-one or logic error.
Why it happens
- 1Slice expression s[low:high] where high exceeds cap(s)
- 2Negative or inverted bounds such as s[5:2]
Fix
Validate bounds before slicing
Validate bounds before slicing
if end > len(data) { end = len(data) }
chunk := data[start:end]Why this works
Clamping end to len(data) ensures the slice expression stays within valid bounds.
Code examples
Safe slicego
end := min(start+size, len(data)) chunk := data[start:end]
Validate manuallygo
if lo > hi || hi > len(s) {
return nil, errors.New("bad bounds")
}
out := s[lo:hi]Recovergo
defer func() {
if r := recover(); r != nil {
log.Println("slice panic:", r)
}
}()Same error in other languages
Sources
Official documentation ↗
Go runtime
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev