Interface Method Parameterization in Go Generics
While exploring Go generics in version 1.18beta2, developers may encounter the error "interface method must have no type parameters" when attempting to define an interface with methods accepting type parameters. This error stems from the design decision to prohibit type parameters in interface method definitions.
The reason behind this restriction lies in the potential for ambiguity and performance implications. Type parameters in interface methods can lead to uncertainty about whether the argument's identity is preserved, the need for exhaustive compile-time tree traversal, or the potential for performance-impacting reflection at runtime.
Moreover, parameterized methods cannot directly implement interfaces, which could introduce confusion.
However, there is a workaround that allows for the use of type parameters within an interface: move the type parameter to the interface type definition itself. This approach preserves the desired functionality while adhering to the design limitations of Go generics.
For example:
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 }
The above is the detailed content of Why Can\'t Go Generics Interface Methods Have Type Parameters?. For more information, please follow other related articles on the PHP Chinese website!