go type_error ai_generated true

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

ID: go/cannot-use-type-without-star

Also available as: JSON · Markdown · 中文
92%Fix Rate
88%Confidence
1Evidence
2023-11-20First Seen

Version Compatibility

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

Root Cause

A function expects a pointer to a type (*T) but receives a non-pointer value (T), causing a type mismatch.

generic

中文

函数期望接收指向类型的指针 (*T),但传入了非指针值 (T),导致类型不匹配。

Official Documentation

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

Workarounds

  1. 95% success Pass the address of the variable: `functionName(&variable)` instead of `functionName(variable)`.
    Pass the address of the variable: `functionName(&variable)` instead of `functionName(variable)`.
  2. 90% success If the variable is not addressable (e.g., map value), copy it first: `tmp := variable; functionName(&tmp)`.
    If the variable is not addressable (e.g., map value), copy it first: `tmp := variable; functionName(&tmp)`.

中文步骤

  1. Pass the address of the variable: `functionName(&variable)` instead of `functionName(variable)`.
  2. If the variable is not addressable (e.g., map value), copy it first: `tmp := variable; functionName(&tmp)`.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Casting requires the value to be addressable; this often leads to another compilation error.

  2. 60% fail

    Modifying library or external function signatures is not always possible or breaks other code.