go runtime_error ai_generated true

恐慌:运行时错误:切片边界超出范围 [:6],容量为4

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
1证据数
2024-03-15首次发现

版本兼容性

版本状态引入弃用备注
go1.21 active
go1.22 active
go1.23 active

根因分析

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

English

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

generic

官方文档

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

解决方案

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

无效尝试

常见但无效的做法:

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

    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% 失败

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