go type_error ai_generated true

cannot use x (variable of type T) as type *T in argument to method

ID: go/method-receiver-type-mismatch

Also available as: JSON · Markdown · 中文
90%Fix Rate
87%Confidence
1Evidence
2023-09-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
go1.20 active
go1.21 active
go1.22 active
go1.23 active

Root Cause

A method with a pointer receiver (*T) is being called with a value receiver (T), or vice versa, and the argument type doesn't match the expected pointer or value type.

generic

中文

具有指针接收器 (*T) 的方法被使用值接收器 (T) 调用,反之亦然,参数类型与预期的指针或值类型不匹配。

Official Documentation

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

Workarounds

  1. 95% success Take the address of the variable: method(&x) if the method expects *T
    Take the address of the variable: method(&x) if the method expects *T
  2. 90% success If the method expects T, dereference the pointer: method(*ptr)
    If the method expects T, dereference the pointer: method(*ptr)

中文步骤

  1. Take the address of the variable: method(&x) if the method expects *T
  2. If the method expects T, dereference the pointer: method(*ptr)

Dead Ends

Common approaches that don't work:

  1. Using a type assertion: x.(*T) 95% fail

    Type assertion works on interfaces, not on concrete types; it will cause a compile error if T is not an interface.

  2. Changing the method receiver to value type (T) 80% fail

    If the method modifies the struct, changing to value receiver will cause those modifications to be lost.

  3. Passing &x directly without checking if x is addressable 75% fail

    If x is not addressable (e.g., return value of a function), &x will cause a compile error.