reflect and generic type or func?

500 views
Skip to first unread message

xie cui

unread,
Feb 5, 2021, 10:05:14 AM2/5/21
to golang-nuts
type String [T any] struct {
str T
}

fmt.Println(reflect.TypeOf(a).Name())

in generic code, what is the output of relfect type name of generic type?

Axel Wagner

unread,
Feb 5, 2021, 11:02:52 AM2/5/21
to xie cui, golang-nuts
It's impossible to tell, as that code is invalid. You didn't define `a`, so we don't know what its type should be. If you intended to add a `var a String[int]`, for example, I would assume it should print something like "String[int]".

--
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/334a7046-7c64-40e7-832e-09d51366c947n%40googlegroups.com.

xie cui

unread,
Feb 7, 2021, 5:45:02 AM2/7/21
to golang-nuts
the branch dev.go2go will print some thing like 'instantiate୦୦String୦string', i will in the release of generic it wouldn't looks like this?

Axel Wagner

unread,
Feb 7, 2021, 6:54:31 AM2/7/21
to xie cui, golang-nuts
No. The go2go tool is a prototype that rewrites generic go code into normal go code, fed to the normal compiler. It generates types and functions with mangled names as you observed (the mangled names need to remain valid Go identifiers, but also shouldn't clash with other names, which is why they look so awkward). And that code is compiled by the normal compiler using the unmodified reflect package, so it sees the mangled auto-generated names.

The actual generics implementation will have a compiler and reflect package that are aware of generics and can thus provide more pleasing type names. As I said, my guess would be that it'll be `String[string]`, mirroring the syntax to instantiate the type.

Reply all
Reply to author
Forward
0 new messages