Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Implementing an Interface with a Generic Method Receiver

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Instantiations:

A generic function or type is instantiated by substituting type arguments for the type parameters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading