Anonymous function with Generic type parameters?

2,230 views
Skip to first unread message

Tajmeet Singh

unread,
Feb 16, 2022, 7:20:45 PM2/16/22
to golang-nuts
I have been experimenting with the generics code for a bit and I came across a situation here I wanted to use a generic func as a type

Consider the following:

I have a few sort functions which I want to use for testing and profiling, for this I use something like this

var sortFuncs = []struct {
        name string
        sFunc func([]int)
}{
        {
                name: "Quick Sort",
                sFunc: sort.Quick,
        },
}

Now this sFun inside the struct expects a function with signature func([]nit)

Consider further that we have made changes to these sort functions and now their signature is something like this

func Quick[T constraints.Ordered](arr []T)

How do I make changes to this anonymous struct and sFunc so that they use the new generic func signature?

Thanks!

Ian Lance Taylor

unread,
Feb 16, 2022, 7:49:32 PM2/16/22
to Tajmeet Singh, golang-nuts
Type parameters are associated with type names. So you would have to
give the anonymous struct a name.

But that doesn't seem likely to help you. A variable can not have
type parameters. Your variable sortFuncs has to be a slice of some
specific instance of the anonymous struct. Given that, you may as
well sortFuncs the same and write "sfunc: sort.Quick[int]".

Ian

Tajmeet Singh

unread,
Feb 16, 2022, 9:09:49 PM2/16/22
to golang-nuts
Thanks for the response Ian.

This makes so much sense now.

On the back of this I have yet another (probably stupid) question - about the type inference at compile time.

Suppose we have a type

type stateFunc[T any] func(T) stateFunc[T]

and a function

func someFunc(înput int) stateFunc[int] {...}

and do something like this for interface compliance checks at compile time

var _ stateFunc = someFunc

Shouldn't the compiler already be able to infer that stateFunc type parameter is int?

Ian Lance Taylor

unread,
Feb 16, 2022, 10:21:35 PM2/16/22
to Tajmeet Singh, golang-nuts
On Wed, Feb 16, 2022 at 6:11 PM Tajmeet Singh <tjgur...@gmail.com> wrote:
>
> Thanks for the response Ian.
>
> This makes so much sense now.
>
> On the back of this I have yet another (probably stupid) question - about the type inference at compile time.
>
> Suppose we have a type
>
> type stateFunc[T any] func(T) stateFunc[T]
>
> and a function
>
> func someFunc(înput int) stateFunc[int] {...}
>
> and do something like this for interface compliance checks at compile time
>
> var _ stateFunc = someFunc
>
> Shouldn't the compiler already be able to infer that stateFunc type parameter is int?

At least for now type inference is only done on function calls.

What you are suggesting is similar to https://go.dev/issue/50285.

Ian
Reply all
Reply to author
Forward
0 new messages