# panic: runtime error: index out of range [5] with length 5 (closure capture)

- **ID:** `go/goroutine-slice-iteration-closure`
- **Domain:** go
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

A goroutine closure captures a loop variable by reference, leading to unexpected index values when the goroutine executes after the loop.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 1.0 | active | — | — |
| 1.22 | active | — | — |

## Workarounds

1. **Copy loop variable to a local variable inside the loop** (95% success)
   ```
   for i := 0; i < 5; i++ {
    i := i
    go func() {
        fmt.Println(i)
    }()
}
   ```
2. **Pass the value as an argument to the goroutine** (95% success)
   ```
   for i := 0; i < 5; i++ {
    go func(val int) {
        fmt.Println(val)
    }(i)
}
   ```

## Dead Ends

- **Using a sleep inside the loop to 'wait' for goroutines** — Does not fix closure capture; goroutines still see final index. (80% fail)
- **Using a different variable name inside the loop without copying** — All goroutines still reference the same variable. (70% fail)
