Home > Article > Backend Development > Why Does Go Throw the Error "type *T is pointer to type parameter, not type parameter" When Using Generics?
This article delves into the intricacies of why the compiler error "type *T is pointer to type parameter, not type parameter" occurs when attempting to compile code involving generics in Go.
In Go generics, a type parameter represents a placeholder for any type that satisfies the specified constraint. Notably, the constraint defines the set of operations available on the type parameter, but it doesn't directly define the properties of any pointer type derived from that type parameter. This is the crux of the error message encountered.
The error message signifies that the method set of *T does not automatically include pointer receiver methods declared on the concrete type being constrained. This means that if the constraint interface requires a pointer receiver method, the concrete type must implement it with a pointer receiver.
In the code snippet provided:
<code class="go">type GS interface { Id() string (*GS) SetId(string) }</code>
<code class="go">var storeA = &MyStore[*A]{}</code>
<code class="go">type MyStore[T GS] struct { values map[string]T } func (s *MyStore[T]) add(item T) {...}</code>
By making these adjustments, the code becomes syntactically and semantically correct.
The above is the detailed content of Why Does Go Throw the Error "type *T is pointer to type parameter, not type parameter" When Using Generics?. For more information, please follow other related articles on the PHP Chinese website!