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 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
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)