go type_error ai_generated true

无法将类型为 T 的变量 x 用作类型 *T 的参数传递给方法

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

ID: go/method-receiver-type-mismatch

其他格式: JSON · Markdown 中文 · English
90%修复率
87%置信度
1证据数
2023-09-12首次发现

版本兼容性

版本状态引入弃用备注
go1.20 active
go1.21 active
go1.22 active
go1.23 active

根因分析

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

English

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

官方文档

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

解决方案

  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)

无效尝试

常见但无效的做法:

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

    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% 失败

    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% 失败

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