generics compile error: struct does not match interface, cannot infer type

582 views
Skip to first unread message

Mike Andrews

unread,
Jun 20, 2022, 8:06:57 AM6/20/22
to golang-nuts
anyone know why this simple case doesn't compile? i'm trying to call a function defined for generic interface type, which fails to compile for struct instance: https://go.dev/play/p/Y3Gdr2ILpK4

Brian Candler

unread,
Jun 20, 2022, 8:44:06 AM6/20/22
to golang-nuts
Type inference doesn't work in all cases.  When required, just be explicit:

        interfaceFunc[string](x)

Mike Andrews

unread,
Jun 20, 2022, 9:21:34 AM6/20/22
to golang-nuts
great, thanks brian, works like a charm. surprisingly, even works in my specific use case calling it like "interfaceFunc[T](x)" generically without being specific like "[string]", wondering why the compiler's inference is like that? is it a flaw or just a limitation of the concept per se?

Mike Andrews

unread,
Jun 20, 2022, 9:26:40 AM6/20/22
to golang-nuts
here's an example more like my specific use case that i just mentioned, with the surprising inference behavior --- https://go.dev/play/p/BNmjlYejawZ

Brian Candler

unread,
Jun 20, 2022, 10:56:19 AM6/20/22
to golang-nuts
In that case, the 'T' is whatever the type argument is to the generic "run" function.  So as long as "run" can infer its argument type, then you're all good.

That's the "easy" case for type inference: an argument of type T.

    func run[T any](t T)

You call run with a string literal, so clearly it's run[string]("howdy")

OTOH, your "interfaceFunc" has a more complex signature:

    func interfaceFunc[T any](x GenericInterface[T])
Reply all
Reply to author
Forward
0 new messages