# panic: runtime error: slice bounds out of range [:5] with capacity 3

- **ID:** `go/panic-runtime-error-slice-bounds-out-of-range-capacity`
- **Domain:** go
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 92%

## Root Cause

Attempting to slice a slice or array beyond its capacity, e.g., s[:5] when cap(s) is only 3.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| go1.20 | active | — | — |
| go1.21 | active | — | — |
| go1.22 | active | — | — |

## Workarounds

1. **Check the capacity before slicing: if cap(s) < 5 { s = append(s, make([]T, 5-cap(s))...) }; result := s[:5]** (95% success)
   ```
   Check the capacity before slicing: if cap(s) < 5 { s = append(s, make([]T, 5-cap(s))...) }; result := s[:5]
   ```
2. **Use copy() to create a new slice with sufficient capacity: dst := make([]T, 5); copy(dst, s)** (93% success)
   ```
   Use copy() to create a new slice with sufficient capacity: dst := make([]T, 5); copy(dst, s)
   ```
3. **Ensure the slice is initialized with sufficient capacity from the start: s := make([]T, 0, 5); s = append(s, ...)** (90% success)
   ```
   Ensure the slice is initialized with sufficient capacity from the start: s := make([]T, 0, 5); s = append(s, ...)
   ```

## Dead Ends

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