[generics] type inference on an interface function param

102 views
Skip to first unread message

dol...@gmail.com

unread,
Aug 6, 2020, 10:31:05 PM8/6/20
to golang-nuts
Hello,

having fun with generics I stumbled upon this failure:

Bryan C. Mills helped me to fix it by forcing the type at the call point. (the comment in the code)

Forcing a type on a var you just declared is a little bit troublesome in this case, but it could be more painful for other cases.

Is that something that could be improved?

Ian Lance Taylor

unread,
Aug 7, 2020, 12:32:42 PM8/7/20
to dol...@gmail.com, golang-nuts
At first glance I don't think that would be a good idea. You want to
infer the type argument to Printer[T] from the type printer[string].
But printer[string] is a struct and Printer[T] is an interface. We
would have to take printer[string], look at the methods, compare them
to the methods of Printer[T], and infer T from the method signatures.
That is a lot of steps.

Although I think we are going to make type inference more powerful, I
think it's important that it always be simple and predictable for
readers of the code. Inferring an interface type argument based on
method types seems to me to be rather subtle.

Ian

dol...@gmail.com

unread,
Aug 8, 2020, 4:17:16 PM8/8/20
to golang-nuts
Thanks for your input.
Clearly it's not the best example, but it surprised me.
With your explanation, I get it. And also, reading my code again, it is confusing.
I always thought that Go could benefit from generics, but clearly, I want to also avoid template meta programming, because it is clearly not fun to read.
And even for this simple example, it takes a few readings to get.
Reply all
Reply to author
Forward
0 new messages