go runtime_error ai_generated true

reflect: call of reflect.Value.FieldByName on zero Value

ID: go/reflect-panic

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

A reflect operation was called on a zero, nil, or unaddressable Value. This happens when reflecting on nil interfaces, uninitialized structs, or trying to set non-pointer values.

generic

Workarounds

  1. 92% success Check reflect.Value.IsValid() before calling methods on it
    v := reflect.ValueOf(x)
    if v.IsValid() && v.Kind() == reflect.Struct {
        field := v.FieldByName("Name")
        if field.IsValid() { ... }
    }

    Sources: https://pkg.go.dev/reflect#Value.IsValid

  2. 90% success Pass a pointer to reflect.ValueOf when you need to set values
    v := reflect.ValueOf(&myStruct).Elem()
    v.FieldByName("Name").SetString("value")  // addressable via pointer

    Sources: https://pkg.go.dev/reflect#Value.Set

Dead Ends

Common approaches that don't work:

  1. Use recover() to catch reflect panics and continue 80% fail

    Catching the panic masks the root cause — the reflected value is wrong, so the operation never produces correct results

Error Chain

Leads to:
Preceded by:
Frequently confused with: