go runtime_error ai_generated true

panic: runtime error: slice bounds out of range [:5] with capacity 3

ID: go/panic-runtime-error-slice-bounds-out-of-range-capacity

Also available as: JSON · Markdown · 中文
92%Fix Rate
88%Confidence
1Evidence
2023-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
go1.20 active
go1.21 active
go1.22 active

Root Cause

Attempting to slice a slice or array beyond its capacity, e.g., s[:5] when cap(s) is only 3.

generic

中文

尝试对切片或数组进行超出其容量的切片操作,例如当 cap(s) 仅为 3 时执行 s[:5]。

Official Documentation

https://go.dev/ref/spec#Slice_expressions

Workarounds

  1. 95% success Check the capacity before slicing: if cap(s) < 5 { s = append(s, make([]T, 5-cap(s))...) }; result := s[:5]
    Check the capacity before slicing: if cap(s) < 5 { s = append(s, make([]T, 5-cap(s))...) }; result := s[:5]
  2. 93% success Use copy() to create a new slice with sufficient capacity: dst := make([]T, 5); copy(dst, s)
    Use copy() to create a new slice with sufficient capacity: dst := make([]T, 5); copy(dst, s)
  3. 90% success Ensure the slice is initialized with sufficient capacity from the start: s := make([]T, 0, 5); s = append(s, ...)
    Ensure the slice is initialized with sufficient capacity from the start: s := make([]T, 0, 5); s = append(s, ...)

中文步骤

  1. 在切片前检查容量:if cap(s) < 5 { s = append(s, make([]T, 5-cap(s))...) }; result := s[:5]
  2. 使用 copy() 创建一个具有足够容量的新切片:dst := make([]T, 5); copy(dst, s)
  3. 确保从一开始就用足够的容量初始化切片:s := make([]T, 0, 5); s = append(s, ...)

Dead Ends

Common approaches that don't work:

  1. Change the slice bounds to a smaller number without checking capacity 70% fail

    Arbitrary reduction may hide the real bug or cause data loss

  2. Ignore the panic and rely on recover() in production 90% fail

    Recovering from a bounds panic is unsafe and may leave state inconsistent

  3. Use append() to extend the slice before slicing 60% fail

    append() may reallocate, but doesn't fix the root cause of accessing beyond capacity