[generics] generic function definition all in one parameter list

105 views
Skip to first unread message

Tor Langballe

unread,
Jul 21, 2020, 6:37:01 PM7/21/20
to golang-nuts
This might have been discussed, but can't find anything about so easy, joined late...

Could generic function definitions be done all in one paramter list using the type keyword?

func IndexOf(slice []type T, find type T) int

or
func IndexOf(slice []type T, find T) int



instead of

func IndexOf[type T](slice []T, find T) int


 
Function calling / instatiating would probably still have a type declaration part in [ ] or whatever ends up being used.

It could get messy with contracts / required interfaces, and might not be parsable, but might be nice not to repeat types if they are longer names.

 



Ian Lance Taylor

unread,
Jul 21, 2020, 6:59:18 PM7/21/20
to Tor Langballe, golang-nuts
A few quick notes.

As you mention, how do constraints work?

If there are multiple type parameters, I think it's not immediately
obvious how the type arguments should be passed.

What about functions that use a type parameter that is not used by any
of the non-type parameters? That's uncommon but it seems like it
could happen.

Ian

Tor Langballe

unread,
Jul 21, 2020, 7:32:49 PM7/21/20
to golang-nuts
For constraints they also could be after type name:

func IndexOf(slice []type T comparable, find T) int
or maybe this is clearer:
func IndexOf(slice []type comparable T, find T) int

This generic type information could be added on leftmost first use of the type in the parameter list or return, and only the type name (i.e T) used if more than once as above.
Multiple type parameters should be just doing this for each parameter:

func IndexOf(slice []type T, find T, range type R) int

types used only in the function but not as a parameter could have an underscore _ as their parameter name, not great, but workable for an edgy case perhaps.


It might have too many problems, but funny how introducing the "type" keyword opens up new possibilities!
Reply all
Reply to author
Forward
0 new messages