Generic instance creation inference

189 views
Skip to first unread message

Steve Heyns

unread,
May 3, 2023, 11:48:37 AM5/3/23
to golang-nuts
Ran into this and I was wondering if it was a bug or not. Assuming "Foo" is an interface with a function of "Bar", then the following function should have a type reference of T and a pointer reference of P that implements the Foo interface, and is bound to the Type of T (https://gotipplay.golang.org/p/BKsA7-6MlHV). 

type  Foo interface {
Bar() string
}

func Update[T any, P interface {
Foo
*T
}]() {


Inside that function :
var t T; t.Bar() // gives
t.Bar undefined (type T has no field or method Bar)

var t T; i:= &t; i.Bar() // Gives
i.Bar undefined (type *T is pointer to type parameter, not type parameter)

But the following passes compile, and creates a new instance of type T, with "i" being the pointer to it.
var t T; var i P; i= &t; i.Bar() // Pass

IMO all three ways should work, but curious as to why they don't

Thanks
Nz

Axel Wagner

unread,
May 3, 2023, 2:20:24 PM5/3/23
to Steve Heyns, golang-nuts
That's a well-known implementation restriction, mentioned in the release notes of Go 1.18:

The Go compiler only supports calling a method m on a value x of type parameter type P if m is explicitly declared by P's constraint interface. Similarly, method values x.m and method expressions P.m also are only supported if m is explicitly declared by P, even though m might be in the method set of P by virtue of the fact that all types in P implement m. We hope to remove this restriction in a future release.

So far, we haven't managed to remove this restriction. It's surprisingly complicated.
I tend to spell that call as `P(&t).Bar()` for what it's worth.

--
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/205934b5-0b7e-4fe5-9912-402fdcb4db1fn%40googlegroups.com.

Steve Heyns

unread,
May 3, 2023, 5:18:36 PM5/3/23
to Axel Wagner, golang-nuts
Thanks for the reference document, and a compressed way of using it !

Cheers
Nz
Reply all
Reply to author
Forward
0 new messages