mor*_*aes 87 reflection go go-reflect
鉴于一个功能,是否有可能得到它的名字?说:
func foo() {
}
func GetFunctionName(i interface{}) string {
// ...
}
func main() {
// Will print "name: foo"
fmt.Println("name:", GetFunctionName(foo))
}
Run Code Online (Sandbox Code Playgroud)
我被告知runtime.FuncForPC会有所帮助,但我不明白如何使用它.
mor*_*aes 152
很抱歉回答我自己的问题,但我找到了一个解决方案:
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))
}
Run Code Online (Sandbox Code Playgroud)
不完全是你想要的,因为它记录了文件名和行号,但这是我在Tideland Common Go Library(http://tideland-cgl.googlecode.com/)中使用"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)
Run Code Online (Sandbox Code Playgroud)
通过获取前一个调用者的函数名称:
import (
"os"
"runtime"
)
func currentFunction() string {
counter, _, _, success := runtime.Caller(1)
if !success {
println("functionName: runtime.Caller: failed")
os.Exit(1)
}
return runtime.FuncForPC(counter).Name()
}
Run Code Online (Sandbox Code Playgroud)