Type Parameters in Interface Methods: A Go Generics Quandary
In Go's pursuit of generics, a peculiar stumbling block emerges: the prohibition of type parameters within interface method definitions. This restriction, encountered by a developer attempting to abstract a key/value store, leaves us wondering why and if a solution exists.
Rationale Behind the Restriction
The Go core team has made a deliberate design decision to disallow type parameters in interfaces for several reasons:
Circumventing the Restriction
While the restriction can be frustrating, it's not insurmountable. The solution proposed in the Type parameters proposal is to move the type parameter into the interface type definition itself:
type Reader[V Unmarshaler] interface { Read(bucket []byte, k ...[]byte) ([][]byte, error) ReadDoc(bucket []byte, factory func() (V, error), k ...[]byte) ([]V, error) } type Unmarshaler interface { UnmarshalKV(v []byte) error }
This approach allows for type-safe generic interfaces while preserving the design constraints of the language.
The above is the detailed content of Can Go Generics Handle Type Parameters in Interface Method Definitions?. For more information, please follow other related articles on the PHP Chinese website!