Name of function pointed to by function pointer?

1,772 views
Skip to first unread message

aro...@gmail.com

unread,
Mar 23, 2012, 4:58:12 PM3/23/12
to golan...@googlegroups.com
Is it possible to dynamically determine the name of a function that a function pointer points to?

For example, I want something like:
func Add(a,b int) int { return a+b }
func Sub(a,b int) int { return a-b }
type Op func(a,b int) int
const (
  ADD = Op(Add)
  SUB = Op(Sub)
)
func (o Op) String() string {
  return reflect.ValueOf(o). ??? .Name()
}

Is this a pipe dream?  I know that methods may be anonymous, so I'm OK with an empty string in this case.

- Augusto

Ian Lance Taylor

unread,
Mar 23, 2012, 5:38:54 PM3/23/12
to aro...@gmail.com, golan...@googlegroups.com
aro...@gmail.com writes:

> Is it possible to dynamically determine the name of a function that a
> function pointer points to?

Not in general, no.

You could do it in specific cases by comparing pointer values. You can
no longer compare func values directly, but you can use unsafe to pull
out the pointer. Of course this won't work for closures, for methods,
in the presence of shared libraries (not supported today, but someday),
etc.

Ian

si guy

unread,
Mar 23, 2012, 11:08:40 PM3/23/12
to golan...@googlegroups.com
You could store the function pointers in a map with the function names as string keys?

roger peppe

unread,
Mar 24, 2012, 11:22:55 AM3/24/12
to Ian Lance Taylor, aro...@gmail.com, golan...@googlegroups.com
On 23 March 2012 21:38, Ian Lance Taylor <ia...@google.com> wrote:
> aro...@gmail.com writes:
>
>> Is it possible to dynamically determine the name of a function that a
>> function pointer points to?
>
> Not in general, no.

actually you can:

func funcName(f interface{}) string {
p := reflect.ValueOf(f).Pointer()
rf := runtime.FuncForPC(p)
return rf.Name()
}

but i don't think it's guaranteed to work, it might be slow, and it's
against the spirit of the language to use it for anything other than
debugging IMHO.

(kudos to gustavo for finding the trick)

mattn

unread,
Mar 24, 2012, 11:32:03 AM3/24/12
to golan...@googlegroups.com, Ian Lance Taylor, aro...@gmail.com
Off topic sorry.

It seems that anonymous function are named like '_func_001'. And it don't avoid redeclaration.

http://play.golang.org/p/-iCocLYyBS

unread,
Mar 24, 2012, 11:46:28 AM3/24/12
to golan...@googlegroups.com
In my opinion, if you want portable non-anonymous functions you need to create a unique variable identifying the function. See http://stackoverflow.com/questions/9643205/how-do-i-compare-two-functions-for-pointer-equality-in-the-latest-go-weekly/9644797#9644797
Reply all
Reply to author
Forward
0 new messages