{
  "id": "go/goroutine-slice-iteration-closure",
  "signature": "panic: runtime error: index out of range [5] with length 5 (closure capture)",
  "signature_zh": "恐慌：运行时错误：索引超出范围 [5]，长度为 5（闭包捕获）",
  "regex": "panic:\\ runtime\\ error:\\ index\\ out\\ of\\ range\\ \\[5\\]\\ with\\ length\\ 5\\ \\(closure\\ capture\\)",
  "domain": "go",
  "category": "runtime_error",
  "subcategory": null,
  "root_cause": "A goroutine closure captures a loop variable by reference, leading to unexpected index values when the goroutine executes after the loop.",
  "root_cause_type": "generic",
  "root_cause_zh": "goroutine 闭包通过引用捕获循环变量，导致 goroutine 在循环后执行时索引值意外。",
  "versions": [
    {
      "version": "1.0",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    },
    {
      "version": "1.22",
      "introduced": null,
      "deprecated": null,
      "removed": null,
      "behavior_change": null,
      "status": "active"
    }
  ],
  "os_specific": {},
  "dead_ends": [
    {
      "action": "Using a sleep inside the loop to 'wait' for goroutines",
      "why_fails": "Does not fix closure capture; goroutines still see final index.",
      "fail_rate": 0.8,
      "condition": "",
      "sources": []
    },
    {
      "action": "Using a different variable name inside the loop without copying",
      "why_fails": "All goroutines still reference the same variable.",
      "fail_rate": 0.7,
      "condition": "",
      "sources": []
    }
  ],
  "workarounds": [
    {
      "action": "Copy loop variable to a local variable inside the loop",
      "success_rate": 0.95,
      "how": "for i := 0; i < 5; i++ {\n    i := i\n    go func() {\n        fmt.Println(i)\n    }()\n}",
      "condition": "",
      "sources": []
    },
    {
      "action": "Pass the value as an argument to the goroutine",
      "success_rate": 0.95,
      "how": "for i := 0; i < 5; i++ {\n    go func(val int) {\n        fmt.Println(val)\n    }(i)\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.88,
  "fix_success_rate": 0.8,
  "resolvable": "true",
  "first_seen": "2024-11-01",
  "last_confirmed": "2025-01-01",
  "last_updated": "2025-01-01",
  "evidence_count": 0,
  "tags": [],
  "locale": "en",
  "aliases": []
}