go runtime_error ai_generated true

panic: runtime error: slice bounds out of range [:6] with capacity 4

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
1Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
go1.21 active
go1.22 active
go1.23 active

Root Cause

Attempting to reslice a slice beyond its capacity, which is a compile-time check bypassed by dynamic index.

generic

中文

尝试对切片进行超出其容量的重新切片,动态索引绕过了编译时检查。

Official Documentation

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

Workarounds

  1. 90% success Use make to pre-allocate slice with sufficient capacity: s := make([]int, 0, 10); then append or reslice within cap.
    Use make to pre-allocate slice with sufficient capacity: s := make([]int, 0, 10); then append or reslice within cap.
  2. 85% success Check capacity before slicing: if cap(s) >= 6 { s = s[:6] } else { /* handle error */ }
    Check capacity before slicing: if cap(s) >= 6 { s = s[:6] } else { /* handle error */ }

中文步骤

  1. 使用 make 预分配足够的容量:s := make([]int, 0, 10);然后追加或重新切片在容量范围内。
  2. 在切片前检查容量:if cap(s) >= 6 { s = s[:6] } else { /* 处理错误 */ }

Dead Ends

Common approaches that don't work:

  1. Adding bounds check with if condition but using wrong variable 65% fail

    Often developers check len(s) but then use cap(s) for slicing, missing the capacity limit.

  2. Using append to extend slice without understanding capacity growth 50% fail

    append may reallocate, but the original slice's capacity remains; slicing after append on old reference still fails.