Understanding Interface Method Type Parameters in Go
In Go generics, interface methods are not permitted to have type parameters. This restriction arises from fundamental design considerations outlined in the Type Parameters proposal.
Why Are Type Parameters Prohibited in Interfaces?
Implementing Generic Abstractions
Although type parameters are not allowed in interface methods, the language provides an alternative approach. You can move the type parameter into the interface type definition itself, as demonstrated below:
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 preserves the desired generic abstraction without violating the interface method type parameter restriction.
The above is the detailed content of Why Can\'t Go Interface Methods Have Type Parameters?. For more information, please follow other related articles on the PHP Chinese website!