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

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

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

解决方案

  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, ...)

无效尝试

常见但无效的做法:

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

    Arbitrary reduction may hide the real bug or cause data loss

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

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

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

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