# 恐慌：运行时错误：索引超出范围 [0]，长度为0（在协程中）

- **ID:** `go/goroutine-slice-concurrent-access`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

多个协程在没有同步的情况下向切片追加元素，导致切片损坏或访问不正确。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.21 | active | — | — |
| 1.22 | active | — | — |

## 解决方案

1. **Use sync.Mutex to protect slice append** (98% 成功率)
   ```
   var mu sync.Mutex
var s []int
for i := 0; i < 10; i++ {
    go func(val int) {
        mu.Lock()
        s = append(s, val)
        mu.Unlock()
    }(i)
}
   ```
2. **Use a channel to collect results** (95% 成功率)
   ```
   ch := make(chan int, 10)
for i := 0; i < 10; i++ {
    go func(val int) {
        ch <- val
    }(i)
}
var s []int
for i := 0; i < 10; i++ {
    s = append(s, <-ch)
}
   ```

## 无效尝试

- **Pre-allocating slice capacity** — Pre-allocation does not prevent concurrent append races; the length field is still modified concurrently. (80% 失败率)
- **Using a local slice per goroutine and merging later** — Merging slices concurrently can still cause races if not synchronized. (70% 失败率)
