tag recommendation moz length descriptions description go reflection go-reflect

recommendation - ¿Cómo obtener el nombre de una función en Go?



title seo length (2)

Dada una función, ¿es posible obtener su nombre? Decir:

func foo() { } func GetFunctionName(i interface{}) string { // ... } func main() { // Will print "name: foo" fmt.Println("name:", GetFunctionName(foo)) }

Me dijeron que runtime.FuncForPC ayudaría, pero no pude entender cómo usarlo.


No es exactamente lo que quiere, ya que registra el nombre de archivo y el número de línea, pero así es como lo hago en mi biblioteca Common Go de Tideland ( http://tideland-cgl.googlecode.com/ ) usando el paquete "runtime":

// Debug prints a debug information to the log with file and line. func Debug(format string, a ...interface{}) { _, file, line, _ := runtime.Caller(1) info := fmt.Sprintf(format, a...) log.Printf("[cgl] debug %s:%d %v", file, line, info)


Perdón por responder mi propia pregunta, pero encontré una solución:

package main import ( "fmt" "reflect" "runtime" ) func foo() { } func GetFunctionName(i interface{}) string { return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() } func main() { // This will print "name: main.foo" fmt.Println("name:", GetFunctionName(foo)) }