[generics] Closure?

99 views
Skip to first unread message

teiva...@gmail.com

unread,
Jun 18, 2020, 2:18:48 PM6/18/20
to golang-nuts
Hello,

I didn't find in the latest draft design any mention of generics with closure and I'm struggling in having something working:

type Foo(type T) struct {}

func bar(type T)() Foo(T) {
   return func() Foo(T) {
      return Foo(T){}
   }()
}

In this example, how can I create a closure that would return a Foo(T)?


Cheers

Bebop Leaf

unread,
Jun 18, 2020, 2:39:09 PM6/18/20
to golang-nuts
Like this:

It is tricky that you need to write `(_ Foo(T))` as the returning value declaration. Otherwise, the current parser consider it as calling the function with argument T and returns a value of type Foo, or in case of `(Foo(T))`, it is considered as `(Foo T)`, which is named return.

This is mentioned partly at https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md#using-generic-types-as-unnamed-function-parameter-types. But I think at lease it should be updated to include return value declaration.

Bryan C. Mills

unread,
Jun 18, 2020, 2:41:38 PM6/18/20
to golang-nuts
I think this is a bug in the parser, related to (but not the same as) https://golang.org/design/go2draft-type-parameters#instantiating-types-in-type-literals.

Adding doubled parentheses seems to make it work (https://go2goplay.golang.org/p/JSQ_8kGOC_A), but the `Format` button doesn't preserve them.

David Riley

unread,
Jun 18, 2020, 2:43:48 PM6/18/20
to teiva...@gmail.com, golang-nuts
I think this probably gets a little closer to what you were going for, but there's a puzzling error that leads me to think the parser doesn't quite understand the instantiation in the return type: https://go2goplay.golang.org/p/gcD609dr21E

----------------

type Foo(type T) struct {}

type FooFunc(type T) func() Foo(T)

func bar(type T)() FooFunc(T) {
return func() Foo(T) {
return Foo(T){}
}
}

----------------

Looks like someone else just posted that naming the return value is a workaround for this parser issue: https://go2goplay.golang.org/p/0Kdfj81Ot3B

----------------

type Foo(type T) struct {}

type FooFunc(type T) func() Foo(T)

func bar(type T)() FooFunc(T) {
return func() (_ Foo(T)) {
return Foo(T){}
}
}

----------------
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/2083e7d6-95f4-4d34-b5c1-6f986d0d4c51o%40googlegroups.com.

Bryan C. Mills

unread,
Jun 18, 2020, 2:45:02 PM6/18/20
to golang-nuts
Reply all
Reply to author
Forward
0 new messages