# 致命错误：并发切片写入

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

## 根因

多个协程在没有同步的情况下追加到同一个切片，导致数据竞争。

## 版本兼容性

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

## 解决方案

1. **Use a mutex to protect slice appends.** (95% 成功率)
   ```
   var mu sync.Mutex
var slice []int

func appendValue(v int) {
    mu.Lock()
    slice = append(slice, v)
    mu.Unlock()
}
   ```
2. **Use a channel to aggregate results from goroutines.** (90% 成功率)
   ```
   ch := make(chan int, 100)
for i := 0; i < n; i++ {
    go func() {
        ch <- compute()
    }()
}
var results []int
for i := 0; i < n; i++ {
    results = append(results, <-ch)
}
   ```

## 无效尝试

- **Using a channel to serialize appends but not draining the channel properly.** — If channel is buffered and not drained, goroutines may block or deadlock. (70% 失败率)
- **Assuming append is atomic.** — append is not atomic; it may read and update the slice header concurrently, causing corruption. (90% 失败率)
