go
runtime_error
ai_generated
true
恐慌:运行时错误:切片边界超出范围 [:5],容量为 3
panic: runtime error: slice bounds out of range [:5] with capacity 3
ID: go/panic-runtime-error-slice-bounds-out-of-range-capacity
92%修复率
88%置信度
1证据数
2023-03-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| go1.20 | active | — | — | — |
| go1.21 | active | — | — | — |
| go1.22 | active | — | — | — |
根因分析
尝试对切片或数组进行超出其容量的切片操作,例如当 cap(s) 仅为 3 时执行 s[:5]。
English
Attempting to slice a slice or array beyond its capacity, e.g., s[:5] when cap(s) is only 3.
官方文档
https://go.dev/ref/spec#Slice_expressions解决方案
-
在切片前检查容量:if cap(s) < 5 { s = append(s, make([]T, 5-cap(s))...) }; result := s[:5] -
使用 copy() 创建一个具有足够容量的新切片:dst := make([]T, 5); copy(dst, s)
-
确保从一开始就用足够的容量初始化切片:s := make([]T, 0, 5); s = append(s, ...)
无效尝试
常见但无效的做法:
-
Change the slice bounds to a smaller number without checking capacity
70% 失败
Arbitrary reduction may hide the real bug or cause data loss
-
Ignore the panic and rely on recover() in production
90% 失败
Recovering from a bounds panic is unsafe and may leave state inconsistent
-
Use append() to extend the slice before slicing
60% 失败
append() may reallocate, but doesn't fix the root cause of accessing beyond capacity