# fatal error: 并发遍历 map 并写入

- **ID:** `go/fatal-error-concurrent-map-iteration-and-map-write`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

一个 goroutine 正在 range 遍历 map，同时另一个 goroutine 写入该 map，运行时检测到并中止。

## 版本兼容性

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

## 解决方案

1. **** (92% 成功率)
   ```
   Hold a sync.RWMutex: mu.RLock(); for k, v := range m { ... }; mu.RUnlock(), and mu.Lock() for writes.
   ```
2. **** (90% 成功率)
   ```
   Snapshot under lock: mu.RLock(); snapshot := make(map[K]V, len(m)); for k, v := range m { snapshot[k] = v }; mu.RUnlock(); then range over snapshot.
   ```

## 无效尝试

- **** — The copy itself races with the writer; the runtime aborts during the copy loop. (85% 失败率)
- **** — Maps have no index operator; this does not compile, and even an equivalent iteration still races. (90% 失败率)
