go runtime_error ai_generated true

panic: interface conversion: interface is nil, not T

ID: go/interface-nil-not-nil

Also available as: JSON · Markdown
90%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Type assertion on nil interface. Common with error interfaces and empty interface{}.

generic

Workarounds

  1. 95% success Use comma-ok pattern for safe type assertion: val, ok := iface.(Type)
    if val, ok := iface.(MyType); ok {
        // use val
    }

    Sources: https://go.dev/ref/spec#Type_assertions

  2. 90% success Check for nil before type assertion: if iface != nil { ... }
    if iface != nil { ... }

    Sources: https://go.dev/ref/spec#Type_assertions

Dead Ends

Common approaches that don't work:

  1. Use recover() to catch the panic 75% fail

    Hides the bug — nil interface means logic error

  2. Initialize to empty value of the type 60% fail

    May hide cases where nil is a valid/expected state

Error Chain

Frequently confused with: