如何在Go中获得一个函数的名字?

给定一个函数,是否有可能得到它的名字? 说:

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

我被告知runtime.FuncForPC会有帮助,但我不明白如何使用它。

对不起回答我自己的问题,但我find了一个解决scheme:

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

不完全是你想要的,因为它logging了文件名和行号,但是这里是我在Tideland Common Go Library( http://tideland-cgl.googlecode.com/ )上使用“运行时”包做的:

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