{
  "id": "go/goroutine-for-range-channel-close",
  "signature": "panic: close of closed channel (in for range)",
  "signature_zh": "恐慌：关闭已关闭的通道（在 for range 中）",
  "regex": "panic:\\ close\\ of\\ closed\\ channel\\ \\(in\\ for\\ range\\)",
  "domain": "go",
  "category": "runtime_error",
  "subcategory": null,
  "root_cause": "Closing a channel that is being ranged over by another goroutine, causing a panic when the range attempts to read from the closed channel.",
  "root_cause_type": "generic",
  "root_cause_zh": "关闭正在被另一个协程 range 的通道，导致 range 尝试从已关闭通道读取时引发恐慌。",
  "versions": [
    {
      "version": "1.20",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "1.21",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "Closing the channel inside the range loop.",
      "why_fails": "Range loop continues until channel is closed, but closing inside causes panic on next iteration.",
      "fail_rate": 0.8,
      "condition": "",
      "sources": []
    },
    {
      "action": "Using a defer close in the sender goroutine that ranges.",
      "why_fails": "If the sender is also the range receiver, closing inside the loop is problematic.",
      "fail_rate": 0.7,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "Use a separate goroutine to close the channel after all sends are done.",
      "success_rate": 1.0,
      "how": "ch := make(chan int)\ngo func() {\n    for i := 0; i < 10; i++ {\n        ch <- i\n    }\n    close(ch)\n}()\nfor v := range ch {\n    fmt.Println(v)\n}",
      "condition": "",
      "sources": []
    },
    {
      "action": "Use a sync.WaitGroup to coordinate closure.",
      "success_rate": 0.95,
      "how": "var wg sync.WaitGroup\nwg.Add(1)\ngo func() {\n    defer wg.Done()\n    for i := 0; i < 10; i++ {\n        ch <- i\n    }\n}()\ngo func() {\n    wg.Wait()\n    close(ch)\n}()\nfor v := range ch {\n    fmt.Println(v)\n}",
      "condition": "",
      "sources": []
    }
  ],
  "workarounds_zh": [],
  "transition_graph": {
    "leads_to": [],
    "preceded_by": [],
    "frequently_confused_with": []
  },
  "official_doc_url": null,
  "official_doc_section": null,
  "error_code": null,
  "verification_tier": "ai_generated",
  "confidence": 0.85,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-12-08",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}