# 致命错误：并发slice追加

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

## 根因

多个协程向同一个slice追加元素而没有同步，导致数据竞争。

## 版本兼容性

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

## 解决方案

1. **Use mutex to protect slice append** (90% 成功率)
   ```
   var mu sync.Mutex
var s []int
mu.Lock()
s = append(s, 1)
mu.Unlock()
   ```
2. **Use channel to collect results** (85% 成功率)
   ```
   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 with make to avoid reallocation** — Append still modifies slice header; concurrent writes race on length. (80% 失败率)
- **Using copy-on-write pattern manually** — Complex and error-prone; still racy without synchronization. (70% 失败率)
