Generics: Using runtime.FuncForPC() to get method name doesn't *seem* to work

167 views
Skip to first unread message

John

unread,
Nov 7, 2022, 12:24:30 PM11/7/22
to golang-nuts
Or maybe I'm just doing something wrong.

I have a struct implementing generics where methods return the next method to execute.

For tests, I wanted to make sure the returned method was the one expected, so  I was using this:

nextStageName := runtime.FuncForPC(reflect.ValueOf(nextStage).Pointer()).Name()
(where "nextStage" is the next method) 

Here is a simple non-generic version where I get what I expect:

result: main.(*AStruct).NextStage-fm):

Here is probably a slightly convoluted generic version that does not:

result: main.(*GenericStruct[...]).Stage.func1

In that version, it seem to give me the name of the method that returned the next method.

Any idea what is (or what I'm doing) wrong?

Cheers.



Ian Lance Taylor

unread,
Nov 7, 2022, 1:02:28 PM11/7/22
to John, golang-nuts
I'm not sure that runtime.FuncForPC is going to work here. What it is
reporting is a function literal defined within the Stage method (that
is what the "func1" means). What is happening is that the Stage
method is returning a function literal that invokes the NextStage
method. This is due to details of how generic functions are compiled,
and may change from release to release. In general FuncForPC is a
fairly low level operation that has no way to avoid these sorts of
compilation details. I don't know if there is a way to do what you
want to do.

Ian

John

unread,
Nov 7, 2022, 1:09:26 PM11/7/22
to golang-nuts
Thanks Ian for being generous with your time in answering this.  I'll see if I can drum up another way to make that check work. 

Cheers and have a good rest of your day.

John

unread,
Nov 7, 2022, 4:04:16 PM11/7/22
to golang-nuts
Note for posterity:

Other methods of method equality fall in the same problem, such as detailed in:

Reply all
Reply to author
Forward
0 new messages