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
80%Fix Rate
85%Confidence
1Evidence
2024-03-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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_expressionsWorkarounds
-
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.
-
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 */ }
中文步骤
使用 make 预分配足够的容量:s := make([]int, 0, 10);然后追加或重新切片在容量范围内。
在切片前检查容量:if cap(s) >= 6 { s = s[:6] } else { /* 处理错误 */ }
Dead Ends
Common approaches that don't work:
-
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.
-
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.