# 恐慌：运行时错误：切片边界超出范围 [:5]，容量为 3

- **ID:** `go/panic-runtime-error-slice-bounds-out-of-range-capacity`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 92%

## 根因

尝试对切片或数组进行超出其容量的切片操作，例如当 cap(s) 仅为 3 时执行 s[:5]。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| go1.20 | active | — | — |
| go1.21 | active | — | — |
| go1.22 | active | — | — |

## 解决方案

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

## 无效尝试

- **Change the slice bounds to a smaller number without checking capacity** — Arbitrary reduction may hide the real bug or cause data loss (70% 失败率)
- **Ignore the panic and rely on recover() in production** — Recovering from a bounds panic is unsafe and may leave state inconsistent (90% 失败率)
- **Use append() to extend the slice before slicing** — append() may reallocate, but doesn't fix the root cause of accessing beyond capacity (60% 失败率)
