generics: how to repeat type in parameters

129 views
Skip to first unread message

Sathish VJ

unread,
Oct 9, 2021, 1:33:10 PM10/9/21
to golang-nuts
How can I repeat the same generics type in the parameters?  I'm getting a "does not match inferred type" error for the code below.

func Print[T Worker](a T, b T) {
fmt.Println(a.Work() + b.Work())
}

func main() {
        c1 := coder{}
        t1 := tester{}
        Print(c1, t1)
}

Compiler Error: type tester of t1 does not match inferred type coder for T

If I flip the parameters that I pass, then the error is now for the second one.  
        Print(c1, t1)
Compiler Error: type coder of c1 does not match inferred type tester for T)


Brian Candler

unread,
Oct 9, 2021, 1:38:00 PM10/9/21
to golang-nuts
"coder" and "tester" are two different defined types, but function Print is defined to take two arguments of the same type.

Even though they implement the same interface, they are not the same type.  I'd say you want to interfaces *instead* of generics:

Brian Candler

unread,
Oct 9, 2021, 1:42:20 PM10/9/21
to golang-nuts
Alternatively, your function can be generic over two different types:

In this trivial example though, I still think interface values are what you want.  There's not much difference in safety, except you could get passed nil interface values.

Sathish VJ

unread,
Oct 9, 2021, 1:48:26 PM10/9/21
to golang-nuts
Makes sense.  Thank you Brian. 
Reply all
Reply to author
Forward
0 new messages