I'm trying to implement an interface while allowing generics. The simplified scenario looks like this:
type ID[T uuid.UUID | string] struct {
...
}
var _ encoding.TextUnmarshaler = (*ID)(nil)
func (id *ID[T]) UnmarshalText(data []byte) error {
...
}
I end up with the error cannot use generic type ID without instantiation
for the var _ ...
line when I run the code, and my IDE tells me that ID
is missing the required method.
Dropping the [T]
in the method receiver head isn't allowed either because of this instantiation issue.
How can I proceed from here?
CodePudding user response:
You can do:
var _ encoding.TextUnmarshaler = (*ID[string])(nil)
https://go.dev/play/p/WmlJ0JEKeVp
Whenever you get the cannot use generic type ... without instantiation
error, then that means that the compiler expects you to explicitly provide the type argument.
A generic function or type is instantiated by substituting type arguments for the type parameters.