如何在 Go 中获取函数的名称?

新手上路,请多包涵

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

 func foo() {
}

func GetFunctionName(i interface{}) string {
    // ...
}

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

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

原文由 moraes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

我找到了一个解决方案:

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

原文由 moraes 发布,翻译遵循 CC BY-SA 4.0 许可协议

不完全是你想要的,因为它记录了文件名和行号,但这是我在我的 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)

原文由 themue 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题