go runtime_error ai_generated true

panic: runtime error: invalid memory address or nil pointer dereference

ID: go/goroutine-nil-pointer-deref

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-09-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.18 active — — —
1.20 active — — —
1.22 active — — —

Root Cause

A spawned goroutine dereferences a nil pointer, often because it captures a variable that hasn't been initialized yet, or a struct field accessed before assignment.

generic

中文

新启动的 goroutine 解引用了空指针,常见原因是捕获了尚未初始化的变量,或在赋值前访问了结构体字段。

Workarounds

  1. 90% success
    Initialize all captured pointers before launching the goroutine, or pass values explicitly as function arguments: go func(cfg *Config) { ... }(cfg)
  2. 88% success
    Use errgroup and return errors instead of panicking; validate pointer non-nil at goroutine entry.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Treats symptom; the goroutine still operates on invalid state and may corrupt downstream logic.

  2. 80% fail

    Hides the bug; other goroutines still crash and root cause is masked.