I'm trying out go generics in 1.18beta2 and I'm trying to write an abstraction layer for key/value store, boltdb. This is what I'm trying to achieve with it.
type Reader interface {
Read(bucket []byte, k ...[]byte) ([][]byte, error)
ReadDoc[V Unmarshaler](bucket []byte, factory func() (V, error), k ...[]byte) ([]V, error)
}
type Unmarshaler interface {
UnmarshalKV(v []byte) error
}
So that I can provide it a factory to create the type when it finds a key/value, unmarshal the data into it and return back a slice of that specific type. Only I get "interface method must have no type parameters" from the compiler. Why are't type parameters allowed in interfaces? Is supporting this planned? This has crushed my dreams... Would have been perfect. It does however work out of interface.
CodePudding user response:
Ran into the same issue earlier today. This seems to be a design decision for the generics/type parameters since there could be multiple "ways" of interpreting a method with type parameters in interface definition (and implementation work).
In some cases it could either mean:
- Identity of the argument is not preserved.
- Need to traverse the whole tree at compile time, which impacts performance.
- Need for reflection at runtime, which impacts performance.
- Parametrized method do not implement interfaces, which would lead to confusion.
You could however move the parameter type definition to the interface type definition if that solves your issue. More information
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
}