go type_error ai_generated true

cannot call pointer method on value / cannot take the address of

ID: go/method-has-pointer-receiver

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

Calling a pointer receiver method on a non-addressable value (like a map value or function return).

generic

Workarounds

  1. 95% success Store the value in a variable first to make it addressable
    val := myMap[key]
    val.PointerMethod()  // val is addressable

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

  2. 88% success Change the method to a value receiver if it doesn't modify the struct
    func (s MyStruct) Method() { ... }  // value receiver, works on non-addressable

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

Dead Ends

Common approaches that don't work:

  1. Use unsafe.Pointer to get address 90% fail

    Unsafe and undefined behavior for non-addressable values

Error Chain

Leads to: