Home  >  Article  >  Backend Development  >  Why Does Go Throw the Error "type *T is pointer to type parameter, not type parameter" When Using Generics?

Why Does Go Throw the Error "type *T is pointer to type parameter, not type parameter" When Using Generics?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 16:46:02167browse

Why Does Go Throw the Error

Go with Generics: Understanding Type Parameters and Constraints

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.

About Type Parameters and Constraints

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 Explained

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.

Solving the Issue

In the code snippet provided:

  1. Constraints: To address the "SetId method has pointer receiver" error, the interface GS should be defined with a pointer receiver:
<code class="go">type GS interface {
    Id() string
    (*GS) SetId(string)
}</code>
  1. Instantiation: The MyStore instantiation should use *A instead of A:
<code class="go">var storeA = &MyStore[*A]{}</code>
  1. Method Modifications: Change the method definitions in MyStore to use T instead of *T:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn