go type_error ai_generated true

interface conversion: interface is nil, not SomeType

ID: go/interface-assertion-nil

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

A type assertion was attempted on a nil interface value. The interface holds no concrete value, so the assertion panics at runtime.

generic

Workarounds

  1. 95% success Use the comma-ok idiom to safely check the assertion
    val, ok := iface.(ConcreteType)
    if !ok {
        // handle nil or wrong type
    }

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

  2. 90% success Add a nil check before the type assertion
    if iface != nil {
        val := iface.(ConcreteType)
    }

    Sources: https://go.dev/doc/effective_go#interface_conversions

Dead Ends

Common approaches that don't work:

  1. Wrap the assertion in a recover() without fixing the root cause 80% fail

    Masking panics hides the nil interface bug — the code path that should set the value is still broken

Error Chain

Leads to:
Preceded by:
Frequently confused with: